您好,他们的我正在try 填充postedby字段创建一个新的 comments . 当我创建一条 comments 时,我将它保存在MongoDB上,还将Comment._id保存在我的特性模型上(作为ObjectID) 然后我发送res.json( comments ) 我可以在发送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);
};```

推荐答案

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

Node.js相关问答推荐

使用NodeJS在S3上传文件时的格式问题

如何在Firebase Cloud Function v2计划函数中设置代码中的时区?

FindOne()返回所有值,而不是一个值

在对象的嵌套数组中使用$lookup,创建多个记录作为响应,mongodb

Prisma 和 Nextjs:重新部署之前内容不会更新

我正在try 在公共目录中使用 Express.js 项目部署 Angular 静态构建

为什么我不能将 id 发送到后端并通过 findByIdAndRemove() 删除项目?

一个非常奇怪的JavaScript heap out of memory问题

try 在 Heroku 中部署 PRN 应用程序并获得 404

来自 child_process.exec 的错误没有这样的设备或地址,管道有帮助.为什么?

后端位于 Docker 容器中时的 SvelteKit SSR fetch()

Socket IOFlutter 未连接

在多个文件 node.js 之间共享和修改变量

Passport 登录和持久会话

用一级 try ... catch 捕获 JavaScript Promise 中的错误

如何使用 Node.js 在服务器端管理多个 JS 文件

按日期时间字段获取最新的 MongoDB 记录

Nodejs将字符串转换为UTF-8

Mongoose - 验证邮箱语法

node.js 中的意外保留字导入