mongodb 如何使用populate保存mongoose上的新数据

nlejzf6q  于 2022-11-28  发布在  Go
关注(0)|答案(1)|浏览(182)

你好,我正在尝试填充postedBy字段创建一个新的评论。当我创建一个评论,我保存它在mongodb上,我也保存我的特征模型上的comment._id(作为objectId),然后我发送res.json(评论)我可以在发送json响应之前填充吗?我也尝试过,但什么都没有发生我的代码-

exports.createComment = async (req, res) => {
  console.log("run?");
  const { featureId } = req.params;
  const { content } = req.body;
  const postedBy = req.auth._id;
  if (!content) {
    return res
      .status(400)
      .send({ error: "Please provide a content with your comment." });
  }
  const comment = new Comment({
    content,
    postedBy,
  });
  await comment.save();
  await comment.populate("postedBy", "_id username");
  Feature.findByIdAndUpdate(
    featureId,
    { $push: { comments: comment._id } },
    { new: true }
  ).exec((err, result) => {
    if (err) {
      return res.json({
        error: errorHandler(err),
      });
    }
  });
  return res.json(comment);
};```
drkbr07n

drkbr07n1#

exports.createComment = async (req, res) => {
console.log("run?");
const { featureId } = req.params;
const { content } = req.body;
const postedBy = req.auth._id;
if (!content) {
  return res
    .status(400)
    .send({ error: "Please provide a content with your comment." });
}
const comment = new Comment({
  content,
  postedBy,
});
await comment.save();

// One of the ways that I use.
let populatedData= await Comment.findById(comment._id).populate("postedBy", "_id username");
console.log(populatedData)

Feature.findByIdAndUpdate(
  featureId,
  { $push: { comments: comment._id } },
  { new: true }
).exec((err, result) => {
  if (err) {
    return res.json({
      error: errorHandler(err),
    });
  }
});
return res.json(comment);
};

相关问题