node.js - 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 方法中选择正确的评论对象,然后更新消息属性?
解决方案
您必须在数据库中找到正确的数据并更新其所需的属性。您可以通过以下方法进行
exports.updateMessage= async (_id,objectId, newMessage) => {
return await TableName.updateOne({_id: _id},{{comments: {$elemMatch: {_id: objectId}$set:{message:newMessage}}});
};
推荐阅读
- sql-server - SSMS 特定页面以及如何到达那里
- azure - Azure 数据工厂计划触发器不同的环境设置
- ios - Firebase - 删除 1 个节点的密钥会影响另一个节点的相同密钥
- swiftui - GeometryReader 和 ZStack 到产品截图
- apache-spark - 为什么我可以过滤我已经在 spark 中删除的列?
- html - Mac 和图像中文件的别名 - 如何让图像作为别名/符号链接工作?
- angular - 清除错误状态
专注 - qlikview - Sum() 在 Qlik Sense 数据加载编辑器中不起作用
- javascript - 如何将按 $week 分组的 mongoDB 结果转换为日期格式?
- c++ - 在 cpp_int 上设置位