【问题标题】:Mongoose add schema into schema using methodMongoose 使用方法将模式添加到模式中
【发布时间】:2020-01-27 17:47:59
【问题描述】:

我正在尝试使用 Node.js 作为服务器端语言和 Mongo DB 构建一个博客。

因此,在我的博客中,人们可以像其他博客一样撰写帖子并将 cmets 添加到帖子中。

每个帖子都会有 cmets,这就是我正在尝试使用我的帖子架构的内容。当有人试图在帖子上写评论时,它会向服务器发送一个 POST 请求,创建一条新评论并将其保存到数据库中。

在我测试时,评论本身已正确保存,但我无法将其附加到帖子架构中。

这是我的 postSchema.js:

const mongoose = require("mongoose");

const postSchema = new mongoose.Schema(
  {
    owner: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true
    },
    title: {
      type: String,
      required: true
    },
    body: {
      type: String,
      required: true
    },
    comments: [
      {
        comment: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Comment"
        }
      }
    ]
  }
);

还有我的commentSchema.js:

const mongoose = require("mongoose");

const commentSchema = new mongoose.Schema(
  {
    owner: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true
    },
    post: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Post",
      required: true
    },
    content: {
      type: String,
      required: true
    }
  }
);

module.exports = Comment = mongoose.model("Comment", commentSchema);

所以 post schema 有 cmets 数组来存储 cmets。并且每次用户添加评论时,它都会创建一个 POST 请求:

router.post("/:id/new_comment", async (req, res) => {
  const { content } = req.body;
  const comment = new Comment({
    content,
    owner: req.user._id,
    post: req.params.id
  });
  try {
    const post = await Post.findOne({ _id: req.params.id });
    await comment.save();
    await post.addComment(comment);
    res.status(201).send({ post, comment });
  } catch (error) {
    res.status(500).send({ error: error.message });
  }
});

所以这个 POST 请求会寻找帖子添加评论,保存评论,并调用 addComment() 将评论连接到帖子的 cmets 数组中。 此处创建的评论将用作 addComment() 函数的参数。

并且 addComment() 函数在 PostSchema.js 文件中,它是:

postSchema.methods.addComment = async function(comment) {
  const post = this;
  post.comments = post.comments.concat({ comment });
  await post.save();
  return post;
};

一切正常,但结果与我的预期不同。 我希望它像

{
    "post": {
        "_id": "5e2e94c9e6ef8100ecfaf665",
        "title": "Test Post",
        "body": "Test Body",
        "owner": "5e2e6bbd18929829e8679cec",
        "comments": [
            {
                "_id": "5e2e98d9587c78444cd600b2",
                "comment": {
                    "_id": "5e2e98d9587c78444cd600b1",
                    "content": "Test Comment",
                    "owner": "5e2e6bbd18929829e8679cec",
                    "post": "5e2e94c9e6ef8100ecfaf665",
                    "__v": 0
                }
            }
        ],
    },
    "comment": {
        "_id": "5e2e98d9587c78444cd600b1",
        "content": "Test Comment",
        "owner": "5e2e6bbd18929829e8679cec",
        "post": "5e2e94c9e6ef8100ecfaf665",
        "__v": 0
    }
}

第一次看起来不错,但是当我尝试保存第二条评论时问题就来了。 之前保存的评论以某种方式更改,如下所示:

{
    "post": {
        "_id": "5e2e94c9e6ef8100ecfaf665",
        "title": "Test Post",
        "body": "Test Body",
        "owner": "5e2e6bbd18929829e8679cec",
        "comments": [
            {
                "_id": "5e2e98d9587c78444cd600b2",
                "comment": "5e2e98d9587c78444cd600b1"
            },
            {
                "_id": "5e2e98d9587c78444cd600b3",
                "comment": {
                    "_id": "5e2e98d9587c78444cd600b2",
                    "content": "Test Comment 2",
                    "owner": "5e2e6bbd18929829e8679cec",
                    "post": "5e2e94c9e6ef8100ecfaf665",
                    "__v": 0
                }
            }
        ],
    },
    "comment": {
        "_id": "5e2e98d9587c78444cd600b2",
        "content": "Test Comment 2",
        "owner": "5e2e6bbd18929829e8679cec",
        "post": "5e2e94c9e6ef8100ecfaf665",
        "createdAt": "2020-01-27T08:01:29.492Z",
        "updatedAt": "2020-01-27T08:01:29.492Z",
        "__v": 0
    }
}

当我创建测试评论 2 时,我保存的第一条评论发生了变化。什么可能导致这种情况? 感谢您阅读这么长的问题。 任何帮助将不胜感激!祝你有美好的一天。

【问题讨论】:

  • 您可以将帖子和评论保存在不同的集合中,并使用帖子 ID 建立关系,而无需在帖子本身中显式保存 cmets。
  • @ArvindDhakad 是的,我知道并且我也尝试过,但我也想知道如何解决我面临的问题。 :D 还是谢谢你的回复

标签: javascript node.js mongodb mongoose mongoose-schema


【解决方案1】:

问题就在这里,您传递的是完整评论而不是它的 id。

  await post.addComment(comment_id); // pass comment id here 

因为在你的帖子模型中

comments: [
      {
        comment: {
          type: mongoose.Schema.Types.ObjectId, // you are storing ObjectId here 
          ref: "Comment"
        }
      }
    ]

因此,您可以将您的 cmets 存储为您的评论 id 的数组,然后您可以在想要填充它时获取完整的 cmets

【讨论】:

  • 感谢您的回复。我只是通过传递我的评论ID再次尝试,结果仍然相同。但是,如果我填充它,我会得到完整的评论吗?比如,使用 .populate() 方法?再次感谢!
  • 是的。试图弄清楚如何将完整的评论存储到 cmets 数组中,而不仅仅是 id
  • 最好的方法是在这里只存储评论 ID 数组,因此,将来您可以直接使用 populate() 获取所有 cmets,如果您想授予权限,例如更新您的评论给用户到时候可以直接使用你的评论收藏
  • 是的,我认为你是对的,因为我刚刚发现我正在做的只是会复制数据。我的意思是将完整的评论存储在 cmets 集合中,我认为我不需要将完整的评论再次存储在我的帖子集合中。谢谢你的帮助! :)
猜你喜欢
  • 2021-06-11
  • 2016-03-17
  • 1970-01-01
  • 2018-09-02
  • 2021-05-24
  • 1970-01-01
  • 2014-12-13
  • 2019-01-06
  • 2020-09-29
相关资源
最近更新 更多