Mon Schema with Ref:文档未使用保存进行更新

问题描述 投票:1回答:1

我有一个博客,我正在尝试为用户添加向博客添加评论的功能。我已经参考我的comment模型创建了一个blog模型。当我尝试在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);
  }
});

以上代码在邮递员中提交至该路线时,导致以下错误:

TypeError: Cannot read property 'concat' of undefined

如下所示,注释很好,并保存到注释文档中的数据库中,但没有填充Blog文档,因此我认为为什么会收到此错误?

[注意,我正在博客的“获取”和“放置”路线中填充用户和评论。如果需要,我可以发帖,也许那里有问题。

javascript mongodb express mongoose
1个回答
0
投票

我想您正在尝试在blogSchemacommentSchema之间建立一对多关系。这意味着您需要在comments中修改blogSchema

© www.soinside.com 2019 - 2024. All rights reserved.