我是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
相反,我得到了这个:-
1条答案
按热度按时间2vuwiymt1#
您的
Item.insertMany
应该是一个异步任务。您需要使用await
(也需要使用async
)或使用then
块。因为你已经在代码中使用了then
块,你可以像这样重构:字符串