我有一个博客,我正在尝试为用户添加向博客添加评论的功能。我引用我的blog
模型创建了一个comment
模型。当我尝试在 Postman 中向 blog
添加评论时,它会将 comment
保存在评论文档中,但不会添加相关的 comment
到我的 blog
文档。我希望我的文档中的博客项目有自己的评论字段,每个评论都有。
评论模型
const commentSchema = mongoose.Schema({
comment: { type: String, required: true },
blog: {
type: mongoose.Schema.Types.ObjectId,
ref: "Blog"
}
});
commentSchema.set("toJSON", {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString();
delete returnedObject._id;
delete returnedObject.__v;
}
});
module.exports = mongoose.model("Comment", commentSchema);
博客模型
const blogSchema = mongoose.Schema({
title: { type: String, required: true },
author: { type: String, required: true },
url: String,
likes: Number,
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
comments: {
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
});
blogSchema.set("toJSON", {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString();
delete returnedObject._id;
delete returnedObject.__v;
}
});
我尝试在其中添加新评论的 Express 代码
blogsRouter.post("/:id/comments", async (request, response, next) => {
try {
const blog = await Blog.findById(request.params.id);
console.log("Blog", blog);
const comment = new Comment({
comment: request.body.comment,
blog: blog._id
});
const result = await comment.save();
console.log("Blog Comments", blog.comments);
blog.comments = blog.comments.concat(result._id);
await blog.save();
response.status(201).json(result.toJSON());
} catch (error) {
next(error);
}
});
在 Postman 中提交到该路由时,上述代码会导致以下错误:
TypeError: Cannot read property 'concat' of undefined
如下所示,评论正常通过,并保存到 Comments 文档中的数据库,但未填充 Blog 文档,因此我想我为什么会收到此错误?
请注意,我正在博客的 Get 和 Put 路由中填充用户和评论。如果需要我可以发帖,也许那里有问题。
最佳答案
我猜您正在尝试在 blogSchema
和 commentSchema
之间建立一对多关系。这意味着您需要修改 blogSchema
中的 comments
:
const blogSchema = mongoose.Schema({
title: { type: String, required: true },
author: { type: String, required: true },
url: String,
likes: Number,
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});
这将允许您使用 concat
或 push
,如下所示:
blog.comments.push(comment);
结果应该是一样的
关于javascript - 带有 Ref : Document Not Updating With Save 的 Mongo 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58897223/