javascript - How to pass field name into update() method of Mongoose? -


i wanna update every field contained in datatochange object reason cannot pass key name update(), mean method not take outside , looking "key" field in database's object. how can it? tried use ${key}, considered error.

changeuserinfofashion = function (id, datatochange, res, callback) {        //var id = id;     _.forin(datatochange, function (value, key) {         key.tostring();         console.log('i going update ' + key + " " + value);         user.update(             {"_id": id},             //here need pass key -->             {key: value},             function (err, results) {                 console.log(results);                 if (err) {                     return callback();                 }                 return res.json({success: true, msg: key + ' changed.'}).status(200);             });     });  }; 

examplae of datatochange

{ name: 'baby', age: 32 } 

no need iterate object , update each field, can use $set operator follows:

changeuserinfofashion = function (id, datatochange, res, callback) {            user.update(         { "_id": id },         { "$set": datatochange },         function (err, results) {             console.log(results);             if (err) { return callback(); }             return res.json({                 success: true,                  msg: json.stringify(datatochange) + ' changed.'             }).status(200);         }     );     }; 

Comments