我将如何使用所有帖子评论填充 mongoDB 帖子模式?

时间:2021-03-24 15:32:10

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

我建立了两种模式,一种用于帖子,一种用于评论。

const PostSchema = new Schema(
  {
    title: { type: String, required: true },
    text: { type: String, required: true },
    author: { type: Schema.Types.ObjectId, ref: 'User', required: true },
    status: { type: Boolean, default: true },
  },
  { timestamps: true }
);

和:

const CommentSchema = new Schema(
  {
    text: { type: String, required: true, minlength: 5 },
    author: { type: String, required: true },
    post: { type: Schema.Types.ObjectId, ref: 'Post' },
  },
  {
    timestamps: true,
  }
);

现在我想发出一个 GET 请求,它会查找所有帖子并用其评论填充每个帖子。到目前为止,我有这个,但我碰壁了。如果我尝试这样做,则无法添加 .toArray(),它甚至不会向 allPosts 添加新字段。

exports.allPosts_GET = (req, res) => {
  Post.find()
    .populate('author')
    .sort('-createdAt')
    .exec((err, allPosts) => {
      if (err) {
        return res.status(500).json({ success: false, msg: err.message });
      } else if (allPosts.length === 0) {
        return res.status(404).json({
          success: false,
          msg: 'No posts find in the database!',
        });
      }
      
      allPosts.map((post) => {
        post.comments = Comment.find({post: post._id}). 
        //to array somehow and populate all posts
        
      });

      console.log(allPostsStore);

      res.status(200).json({ success: true, posts: allPosts });
    });
};

1 个答案:

答案 0 :(得分:0)

所以我想出了一个解决方案,我更新了我的 Post 架构,其中包含一个引用评论 ID 的数组。像这样:

const PostSchema = new Schema(
  {
    title: { type: String, required: true },
    text: { type: String, required: true },
    author: { type: Schema.Types.ObjectId, ref: 'User', required: true },
    comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
    status: { type: Boolean, default: true },
  },
  { timestamps: true }
);

然后当您发表新评论时,您将其引用到帖子中,并将其保存到评论数组中,如下所示:

exports.createNewComment_POST = (req, res) => {
  const { text, author, postID } = req.body;

  const newComment = new Comment({
    text,
    author,
    post: postID,
  });

  newComment
    .save()
    .then((comment) => {
      Post.findByIdAndUpdate(
        postID,
        { $push: { comments: comment._id } },
        { new: true, useFindAndModify: false },
        (err, post) => {
          if (err) {
            return res.status(500).json({ success: false, msg: err.message });
          }
          res.status(200).json({ success: true, comment });
        }
      );
    })
    .catch((err) => {
      res.status(500).json({ success: false, msg: err.message });
    });
};

获取所有带有评论的帖子,您只需使用 find()populate(),如下所示:

exports.allPosts_GET = (req, res) => {
  Post.find()
    .populate('author', '-password')
    .populate('comments')
    .sort('-createdAt')
    .exec((err, posts) => {
      if (err) {
        return res.status(500).json({ success: false, msg: err.message });
      } else if (posts.length === 0) {
        return res.status(404).json({
          success: false,
          msg: 'No posts find in the database!',
        });
      }
      res.status(200).json({ success: true, posts: posts });
    });
};