简体   繁体   中英

how to update nested array of object in mongodb

Here is my db collection in mongoDB. I am using mongoose to update the data inside the comments array

{
        "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
    }

here i want to update the first comment by using comment._id: 63bbdbdb7018eabb752c0e58

how can i update the single comment by using comment._id ;

use-case: when user want to update his/her comment by using comment._id

here i want to update the first comment by using comment._id: 63bbdbdb7018eabb752c0e58

how can i update the single comment by using comment._id ;

use-case: when user want to update his/her comment by using comment._id

Please, read the following docs: 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' } }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM