首页 > 解决方案 > Mongoose 在对象数组中设置对象属性

问题描述

我有一个由 Post 组成的文件。每个帖子都有一个评论数组,每个评论都是一个对象。所以我的文件看起来像这样

在此处输入图像描述

现在,我希望能够更新给定 Comment 对象中的 message 属性。

所以我将使用 $set 方法,但我将如何选择特定对象。目前,我未完成的方法看起来像这样

export const editComment = async (req, res) => {
  const { id } = req.body;

  const post = await Post.findById(req.params.id);

  const _id = post.id;

  const postComments = post.comments.map((comment) => comment._id);

  const commentIndex = postComments.indexOf(id.id);

  const message = post.comments[commentIndex].message;

    try {
      await Post.updateOne(
        { _id },
        {
          $set: {
            // Action to update the comment
          },
        },
        { new: true }
      );
      res.status(200).json({ message: post });
    } catch (error) {
      res.status(400).json({ error: error.message });
    }
  }

我认为选择正确的评论索引是一个好的开始,但我将如何在 $set 方法中选择正确的评论对象,然后更新消息属性?

标签: node.jsmongodbmongoose

解决方案


您必须在数据库中找到正确的数据并更新其所需的属性。您可以通过以下方法进行

exports.updateMessage= async (_id,objectId, newMessage) => {
    return await TableName.updateOne({_id: _id},{{comments: {$elemMatch: {_id: objectId}$set:{message:newMessage}}});
};

推荐阅读