每次使用节点app.js启动服务器时,都会在数据库中创建同一对象的新副本。在下面的代码中,它创建测试博客的次数与使用节点app.js启动服务器.How的次数一样多,我能修复这个问题吗?
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切换到db blog_app db.blogs.find() { "_id“:ObjectId("5dc2a990cebaeb07d43653ac")、”标题“:”测试博客“、”图片“:"https://unsplash.com/photos/-GzyUGKhjBY”、“主体”:“这是一个测试应用。”,“日期”:ISODate("2019-11-06T11:08:00.162Z"),"__v“:0}{{ "_id”:ObjectId(“5dc2ad48d1865088eed3881”),“标题”:“测试博客”、“图片”:"https://unsplash.com/photos/-GzyUGKhjBY“、”正文“:”这是一个测试应用“、”日期“:ISODate("2019-11-06T11:13:24.344Z")、"__v”:{ "_id“:ObjectId(”5dc2ae3f1f12100a748fbb6“)、”标题“:”测试博客“、”图像“:"https://unsplash.com/photos/-GzyUGKhjBY",“ISODate”(“2019-11-06T11:27:59.182Z”),"__v“:0}{ "_id”:ObjectId("5dc2ced6dbd5e902487e3241"),“标题”:“测试博客”:“图像”:"https://unsplash.com/photos/-GzyUGKhjBY",“body:”ISODate("2019-11-06T13:47:02.818Z"),{ "__v“{ "_id”:ObjectId(“5dc2cf09a30522541f30a9”),“标题”:“测试博客”,“图像”:"https://images.unsplash.com/photo-1494256997604-768d1f608cac?ixlib= _id“主体:”这是一个测试应用“,"date”:ISODate("2019-11-06T13:47:53.972Z"),“__v”:0}
发布于 2019-11-06 14:23:24
这是因为您的代码中有这些行,它会在每个应用程序运行时创建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记录一次,最好在options.upsert = true中使用Model.findOneAndUpdate。它将找到并更新它,或者在没有找到记录的情况下创建一个新的记录。
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});https://stackoverflow.com/questions/58731837
复制相似问题