简体   繁体   中英

Attempt to update array of object in mongodb

Here is what I'm trying:

contactModel.update({
            'user_id': req.params.user_id,
            'contacts.contact_id': req.params.id
        }, {
            $set: {
                'contacts.$.name': req.body.contact.name,
                'contacts.$.phone_number': req.body.contact.phone_number
            }
        })

But the code is only for updating specific key. I want to update it based on dynamic key. If name is coming in req.body then it should update only name both are coming, so it should update both.

Fill dinamically the update object with keys found in req.body

   var obj = {};

   for(var i in req.body.contact){
     obj["contacts.$."+i] = req.body.contact[i];
   }

   contactModel.update({
        'user_id': req.params.user_id,
        'contacts.contact_id': req.params.id
    }, {
        $set: obj
    })

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