javascript - 带有 Ref : Document Not Updating With Save 的 Mongo 模式

标签 javascript mongodb express mongoose

我有一个博客,我正在尝试为用户添加向博客添加评论的功能。我引用我的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 路由中填充用户和评论。如果需要我可以发帖,也许那里有问题。

最佳答案

我猜您正在尝试在 blogSchemacommentSchema 之间建立一对多关系。这意味着您需要修改 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"
        }
    ]
});

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

blog.comments.push(comment);

结果应该是一样的

关于javascript - 带有 Ref : Document Not Updating With Save 的 Mongo 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58897223/

相关文章:

javascript - 仅当 gif 从顶部或底部进入视口(viewport)时才播放

javascript - 需要函数对 htm 页面中生成的 <li> 进行排序

javascript - nodeJS 创建动态数组并用作响应

javascript - Fancybox 3 设置超时?

javascript - 单击按钮时自动聚焦到输入(适用于 AMP 文章)

javascript - 通过 Node API 将值从 html 表单传递到另一个(重定向页面)

javascript - 使用 nodejs 创建一个 .json 文件

mongodb - 副本集的 mongoimport 命令是否需要包括仲裁者在内的所有副本集成员?

node.js - 渲染页面,同时使 http 请求变得明确

node.js - Express.js 可以设置 localhost :3000 and localhost:3000/as different routes?