如何使用猫鼬更新数组中的对象字段 [英] How to update field of object in array with Mongoose

查看:45
本文介绍了如何使用猫鼬更新数组中的对象字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过 id 找到一个 房间,并将 received 字段更新为 true,其中 userid 等于 xx.

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

文档在这里:

{
    "_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.****

推荐答案

您需要 位置$运算符:

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

这篇关于如何使用猫鼬更新数组中的对象字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆