Javascript Mongoose使用方法将模式添加到模式中

Javascript Mongoose使用方法将模式添加到模式中,javascript,node.js,mongodb,mongoose,mongoose-schema,Javascript,Node.js,Mongodb,Mongoose,Mongoose Schema,我正在尝试构建一个博客,使用Node.js作为服务器端语言,使用mongodb 因此,在我的博客中,人们可以像其他博客一样写文章和添加评论 每一篇文章都会有评论,这就是我试图用我的文章模式。当有人试图在帖子上写评论时,它会向服务器发送一个帖子请求,创建一个新的评论并将其保存到数据库中 当我进行测试时,注释本身被正确保存,但我在将其附加到post模式时遇到了问题 这是我的postSchema.js: const mongoose = require("mongoose"); const post

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

因此,在我的博客中,人们可以像其他博客一样写文章和添加评论

每一篇文章都会有评论,这就是我试图用我的文章模式。当有人试图在帖子上写评论时,它会向服务器发送一个帖子请求,创建一个新的评论并将其保存到数据库中

当我进行测试时,注释本身被正确保存,但我在将其附加到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"
        }
      }
    ]
  }
);
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);
和我的commentSchema.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"
        }
      }
    ]
  }
);
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);
所以PostSchema有comments数组来存储注释。每次用户添加评论时,都会创建一个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请求将查找POST以添加注释、保存注释,并调用addComment()将注释连接到POST的comments数组中。 此处创建的注释将用作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

  await post.addComment(comment_id); // pass comment id here 
因为在你的帖子里

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

因此,您可以将注释存储为注释id的数组,然后您可以在需要填充时获取完整的注释

您可以将帖子和注释保存在不同的集合中,并使用帖子id建立关系,而无需将注释显式保存在帖子中。@ArvindDhakad是的,我知道,我也尝试过了,但我也想知道如何解决我面临的问题谢谢你的回复。我只是通过传递我的评论id再次尝试,结果仍然是一样的。但是如果我填充它,我会得到完整的评论吗?比如,使用.populate()方法?再次感谢!是的。尝试找出如何将完整注释存储到注释数组中,而不仅仅是idbest方法,正如您在此处所做的那样,在此处仅存储注释id数组,因此,将来您可以使用populate()直接获取所有注释如果你想给用户更新你的评论这样的权限,你可以直接使用你的评论集。是的,我认为你是对的,因为我刚刚发现我所做的只是复制数据。我的意思是,它将完整的评论存储在评论集合中,我不认为我需要在我的帖子集合中再次存储完整的评论。谢谢你的帮助!:)