How to update field of object in array with Mongoose

孤街浪徒 提交于 2021-01-29 14:50:36

问题


I need to find a room by id and update received field to true where user id equals to xx.

The document is here:

{
    "_id" : ObjectId("5e5d0d870fc69641a41a3c65"),
    "users" : [ 
        ObjectId("5e57d64d92cc878760086980"), 
        ObjectId("5e57d64592cc87876008697e")
    ],
    "messages" : [ 
        {
            "_id" : ObjectId("5e67834b6c8b2d356a4ad9fd"),
            "text" : "Hello",
            "user" : ObjectId("5e57d64d92cc878760086980"),
            "createdAt" : ISODate("2020-03-10T12:08:43.006Z"),
            "sent" : true,
            "received" : false
        }, 
        {
            "_id" : ObjectId("5e6783076c8b2d356a4ad9fc"),
            "text" : "Hello",
            "user" : ObjectId("5e57d64d92cc878760086980"),
            "createdAt" : ISODate("2020-03-10T12:07:35.544Z"),
            "sent" : true,
            "received" : true
        }
    ],
    "createdAt" : ISODate("2020-03-02T13:43:35.522Z"),
    "updatedAt" : ISODate("2020-03-10T12:08:43.006Z"),
    "unReads" : {
        "5e57d64d92cc878760086980" : 1,
        "5e57d64592cc87876008697e" : 5
    },
    "__v" : 0
}

****It looks like your post is mostly code; please add some more details.****


回答1:


You need the positional $ operator:

Model.update({_id: ObjectId("5e5d0d870fc69641a41a3c65"), "messages.user": ObjectId("5e57d64d92cc878760086980")}, { $set: { "messages.$.received": true } })


来源:https://stackoverflow.com/questions/60617201/how-to-update-field-of-object-in-array-with-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!