如何在Mongoose保存新评论时用populate填充postedBy字段
解决MongoDB创建评论后填充postedBy字段的问题
你当前代码里的populate调用没生效,核心原因是**populate()方法默认返回填充后的新文档,不会修改原有的comment对象**,直接调用后原变量还是未填充的状态。
修复步骤
修正populate的调用方式
把原代码中的:await comment.populate("postedBy", "_id username");改成以下两种方式之一:
- 方式一(推荐,适配Mongoose新版本):重新赋值给comment变量
comment = await comment.populate("postedBy", "_id username"); - 方式二(仅兼容Mongoose 5及以下版本):使用
execPopulate()直接修改原对象await comment.populate("postedBy", "_id username").execPopulate();
- 方式一(推荐,适配Mongoose新版本):重新赋值给comment变量
修复Feature更新的回调问题
原代码中Feature.findByIdAndUpdate用了回调函数,可能会在res.json(comment)之后执行,如果更新出错,会出现"已发送响应"的报错。建议改成async/await方式并统一异常处理。
修改后的完整代码
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." }); } try { const comment = new Comment({ content, postedBy, }); await comment.save(); // 获取填充后的评论文档 comment = await comment.populate("postedBy", "_id username"); // 异步更新Feature的comments数组 await Feature.findByIdAndUpdate( featureId, { $push: { comments: comment._id } }, { new: true } ); return res.json(comment); } catch (err) { return res.json({ error: errorHandler(err), }); } };
内容的提问来源于stack exchange,提问作者Rohan Srivastava
相关产品推荐
相关产品推荐

