带有参考的Mongo架构:文档未通过保存进行更新

时间:2019-11-17 03:23:19

标签: javascript mongodb express mongoose

我有一个博客,我正在尝试为用户添加向博客添加评论的功能。我已经参考我的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 Code

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

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

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

1 个答案:

答案 0 :(得分:1)

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

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"
        }
    ]
});

这将允许您使用concatpush,如下所示:

blog.comments.push(comment);

结果应该相同