我正在设置博客,但我无法获取与个别博客帖子相关的评论数据。我正在使用Mongoose和Express。我正在尝试创建一个新帖子并将其推送到博客数组,但该关联不保存。当我拉起Mongo shell时,我可以单独看到我的数据库中的注释和博客对象,但它们在数据库中没有关联。但是,它们在我的路线中正确显示在控制台中。
以下是我在不同文件中的两个相关模式。
评论架构:
var mongoose = require("mongoose");
var commentSchema = new mongoose.Schema({
author: String,
desc: String,
posted: {type: Date, default: Date.now()}
});
module.exports = mongoose.model("Comment", commentSchema);
博客架构:
var mongoose = require("mongoose");
var blogSchema = new mongoose.Schema({
author: String,
title: String,
desc: String,
posted: {type: Date, default: Date.now()},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});
module.exports = mongoose.model("Blog", blogSchema);
路线:
app.post("/blogs/:id/comments", function(req, res){
Blog.findById(req.params.id, function(err, blog){
if(err){
// console.log(err);
res.redirect("/blogs");
} else {
Comment.create(req.body.comment, function(err, comments){
if(err){
console.log(err);
} else {
blog.comments.push(comments);
blog.save();
console.log(blog);
res.redirect("/blogs/" + blog._id);
}
});
}
});
});
来自上面的控制台结果:
{ _id: 5a3ef348fcdd624a0c8416fb,
title: 'Ah, a new post!',
author: 'Lefty',
desc: 'Here we are trying to see about fixing the issue with comments not being associated to the blog posts, but still being created.',
__v: 0,
comments:
[ { _id: 5a3f06c0f33db14984baca92,
desc: 'Save the turtles.',
author: 'April',
__v: 0,
posted: 2017-12-24T01:45:16.864Z } ],
posted: 2017-12-24T00:21:34.514Z }
以下是我的Mongo shell中的信息:
> db.blogs.find()
{ "_id" : ObjectId("5a3ef348fcdd624a0c8416fb"), "title" : "Ah, a new post!", "author" : "Lefty", "desc" : "Here we are trying to see about fixing the issue with comments not being associated to the blog posts, but still being created.", "comments" : [ ], "posted" : ISODate("2017-12-24T00:21:34.514Z"), "__v" : 0 }