如何更新嵌套数组MongoDb Node js中的必填字段

时间:2019-01-09 14:45:29

标签: javascript node.js mongodb mongoose-schema

如何查找和更新数据数组中的字段

    "_id" : ObjectId("5bfe6df9777d13255bb2ad7c"),
    "program_id" : ObjectId("5b7bcc8520a2b13177b4d92e"),
    "week_id" : "2018.10.48",
    "month" : 10.0,
    "week_count" : 48.0,
    "year" : 2018.0,
    "data" : [ 
        {
            "_id" : ObjectId("5bfe6df9c1e35824dfcce39f"),
            "date" : 27.0,
            "user_ids" : [ 
                {
                    "checkin_time" : 1543400937337.0,
                    "by" : ObjectId("5bb2aa12460b5f2ef97388e6"),
                    "checkin_by" : ObjectId("5bf7dd8387550226071eda5c"),
                    "checkin_status" : 1.0,
                    "point" : 1.0
                }, 
                {
                    "checkin_time" : 1543400937337.0,
                    "by" : ObjectId("5bb453b44817792ec972c1ab"),
                    "checkin_by" : ObjectId("5be7dd8387550226071eda5c"),
                    "user_utc_checkin_time" : 1543401130940.0,
                    "user_time_zone" : "Asia/Kolkata",
                    "checkin_status" : 1.0,
                    "point" : 1.0
                }, 
                {
                    "checkin_time" : 1543400937337.0,
                    "by" : ObjectId("5bed113bcd1c075e045aa79e"),
                    "checkin_by" : ObjectId("5bed113bcd1c075e045aa79e"),
                    "user_utc_checkin_time" : 1543401594869.0,
                    "user_time_zone" : "Asia/Kolkata",
                    "checkin_status" : 1.0,
                    "point" : 1.0
                }
            ]
        }
    ]

我正在使用

db.collectionName.findAndUpdate(
     {"data.user_ids.checkin_by":mongoose.Types.ObjectId(a) },  
     { $set :
        { "data.user_ids.$.checkin_status":2 }
     }
   )

1 个答案:

答案 0 :(得分:0)

尝试使用此:

db.collectionName.update(
{"data.user_ids.checkin_by":mongoose.Types.ObjectId(a) },
{"$set":{"data.user_ids.$.checkin_status":2 }}
)