node.jsdatabasemongodbmongoosepopulate

How to use populate on saving new data on mongoose


Hello their I am trying to populate postedBy field on creating a new comment. When i create a comment i save it on mongodb and also I save comment._id on my feature model (as objectId) then i am sending res.json(comment) Can i populate before sending json response? I also tried but nothing happened My code-

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);
};```


Solution

  • 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);
    };