Mongodb正在创建对象的副本



每次使用node app.js启动服务器时,都会在数据库中创建同一对象的新副本。在我下面的代码中,它创建测试博客的次数与节点app.js启动服务器的次数一样多。我该如何解决这个问题?

var express    = require("express"),
mongoose   = require("mongoose"),
bodyParser = require("body-parser"),
app        = express();
mongoose.connect('mongodb://localhost:27017/blog_app', {useNewUrlParser: true, useUnifiedTopology: true});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
var blogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
date: {
type: Date,
default: Date.now
}
});
var Blog = mongoose.model("Blog", blogSchema);
Blog.create({
title: "Test Blog",
image: "https://images.unsplash.com/photo-1494256997604-768d1f608cac?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2202&q=80",
body: "This is a test app."
});

// INDEX route
app.get("/", function(req, res){
res.redirect("/blogs");
});
app.get("/blogs", function(req, res){
// res.render("index");
Blog.find({}, function(err, blogs){
if(err){
console.log("ERROR!");
} else {
res.render("index", {blogs: blogs});
}
})
});

app.listen(3000, function(){
console.log("SERVER HAS STARTED!");
});

使用blog_app已切换到dblog_appdb.blogs.find(({"_id":ObjectId("5dc2a990cebaeb07d43653ac"(,"title":"测试博客","image":"https://unsplash.com/photos/-GzyUGKhjBY","body":"这是一个测试应用程序。","日期":ISODate("2019-11-06T11:08:00.162Z"(,"__v":0}{"_id":ObjectId("5dc2aad48d1865088eed3881"(,"title":"测试博客","image":https://unsplash.com/photos/-GzyUGKhjBY","body":"这是一个测试应用程序。","日期":ISODate("2019-11-06T1:13.24.344Z"(,"__v":0}{"_id":ObjectId("5dc2ae3f1f1210a748fdbb6"(,"title":"测试博客","image":https://unsplash.com/photos/-GzyUGKhjBY","body":"这是一个测试应用程序。","日期":ISODate("2019-11-06T11:27:59.182Z"(,"__v":0}{"_id":ObjectId("5dc2ced6dbd5e902487e3241"(,"title":"测试博客","image":"https://unsplash.com/photos/-GzyUGKhjBY","body":"这是一个测试应用程序。","日期":ISODate("2019-11-06T13:47:02.818Z"(,"__v":0}{"_id":ObjectId("5dc2cf09a3052102541f30a9"(,"title":"测试博客","image":https://images.unsplash.com/photo-1494256997604-768d1f608cac?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=裁剪&w=2202&q=80","body":"这是一个测试应用程序。","日期":ISODate("2019-11-06T13:47:53.972Z"(,"__v":0}

这是因为您的代码中有这些行,所以它会在每次运行的应用程序上创建Test Blog

Blog.create({
title: "Test Blog",
image: "https://images.unsplash.com/photo-1494256997604-768d1f608cac?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2202&q=80",
body: "This is a test app."
});

如果您想只创建一次Test Blog记录,最好将Model.findOneAndUpdate与options.upsert = true一起使用。它会找到记录并更新它,或者如果还没有找到记录,它会创建一个新的记录。

Blog.findOneAndUpdate({name: "Test Blog"}, {
title: "Test Blog",
image: "https://images.unsplash.com/photo-1494256997604-768d1f608cac?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2202&q=80",
body: "This is a test app."
}, {upsert: true});

最新更新