【问题标题】:how to update nested array of object in mongodb如何更新mongodb中的嵌套对象数组
【发布时间】:2023-01-12 17:31:00
【问题描述】:

`这是我在 mongodb 中的数据库集合。我正在使用 mongoose 更新 cmets 数组中的数据

{ "author": { "email": "user@example.com", "userName": "John" }, "_id": "63bc20741475b40323d6259f", "title": "this is blog", "description": "description", "blogBanner": "https://github.com//routers/userRouter.js", "views": "0", "comments": [ { "userId": "63b919840ae5303938fb1c17", "comment": "first comment", "_id": "_id:63bbdbdb7018eabb752c0e58 }, { "userId": "63b919840ae5303938fb1c17", "comment": "second comment", "_id": "63bbdbdb7018eabb752ce55" } ], "reaction": [ { "userEmail": "gias@gmail.com", "react": "love" } ], "date": "2023-01-09T14:09:32.810Z", "__v": 0 }

在这里我想通过使用更新第一条评论评论_id:63bbdbdb7018eabb752c0e58

如何使用 comment _id 更新单个评论;

用例:当用户想要使用评论 _id 更新他/她的评论时

在这里,我想使用 comment_id:63bbdbdb7018 abb752c0e58 更新第一条评论

如何使用 comment _id 更新单个评论;

用例:当用户想通过使用评论 _id 来更新他/她的评论时

【问题讨论】:

    标签: mongodb object mongoose nested updating


    【解决方案1】:

    请阅读以下文档: https://www.mongodb.com/docs/manual/reference/operator/update/positional/#update-documents-in-an-array

    Model.update(
     {  
     '_id': '63bc20741475b40323d6259f',
     'comments._id':'63bbdbdb7018eabb752ce55' 
    },
      { $set: { "comments.$.comment" : 'Edited Text' } }
    )
    

    【讨论】: