mongodb 如果集合中没有项目,则插入数据,但是数据会在集合中插入两到三次,如何解决此问题?

k5hmc34c  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(101)

我是mongoose和node.js以及MERN堆栈的新手。如果集合中没有项目,则插入数据。但是数据会在集合中插入两到三次。如何解决这个问题?列表.ejs:-

<%- include('header') %>
    <div class="box" id="heading">
        <h1>
            <%= listTitle %>
        </h1>
    </div>

    <div class="box">
        
        <% newListItems.forEach(item=> { %>
            <div class="item">
                <input type="checkbox">
                <p>
                    <%= item.name %>
                </p>
            </div>
            <% }); %>

                <form class="item" action="/" method="post">
                    <input type="text" name="newItem" placeholder="New Item" autocomplete="off">
                    <button type="submit" name="list" value="<%= listTitle %>">+</button>
                </form>
    </div>

    <%- include('footer') %>

字符串
app.js文件:-

const express = require('express');
const bodyParser = require('body-parser');
const date = require(__dirname + '/date.js');
const mongoose = require('mongoose');
mongoose.connect("mongodb://127.0.0.1:27017/todoListDB").then(() => console.log('connected')).catch(e => console.log(e))

const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

const itemSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    }
});
const Item = new mongoose.model('Item', itemSchema);

// Item.insertMany([
//     { name: "Welcome to your Todo List" },
//     { name: "Hit '+' button to add a new item" },
//     { name: "<--Hit this to check" },
// ]);

const workItems = [];

app.get("/", (req, res) => {
    const day = date.getDate();
    Item.find({}).then(foundItems => {
        if (foundItems.length === 0) {
            Item.insertMany([
                { name: "Welcome to your Todo List" },
                { name: "Hit '+' button to add a new item" },
                { name: "<--Hit this to check" },
            ]);
            res.redirect("/")
        } else {
            res.render("list", { listTitle: day, newListItems: foundItems });
        }
    })
});

app.post("/", (req, res) => {
    if ((x = req.body.newItem) !== "") {
        if (req.body.list === 'Work List') {
            workItems.push(x);
            res.redirect("/work");
        } else {
            newListItems.push(x);
            res.redirect("/");
        }
    } else {
        res.redirect("/");
    }
});

app.get("/work", (req, res) => {
    res.render("list", { listTitle: "Work List", newListItems: workItems });
});

app.post("/work", (req, res) => {
    res.redirect("/work");
});

app.get("/about", (req, res) => {
    res.render("about", { listTitle: "About Me" });
});

app.listen(3000, () => {
    console.log("Server running on http://127.0.0.1:3000");
});


如果数据库是空的,我希望它只插入一次数据。当我重新加载我的页面时,它应该给予我这个:-x1c 0d1x
相反,我得到了这个:-

2vuwiymt

2vuwiymt1#

您的Item.insertMany应该是一个异步任务。您需要使用await(也需要使用async)或使用then块。因为你已经在代码中使用了then块,你可以像这样重构:

Item.insertMany([
   { name: "Welcome to your Todo List" },
   { name: "Hit '+' button to add a new item" },
   { name: "<--Hit this to check" },
]).then((result) =>{
    res.redirect("/");
}).catch((error) =>{
   console.log(error);
});

字符串

相关问题