boooni boooni - 4 months ago 5
Node.js Question

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

I wanna update every field contained in dataToChange object but for some reason I cannot pass key name into update(), I mean that the method does not take it from the outside and it is looking for "key" field in the database's object. How can I do it? I tried to use

${key}
, but it is considered as an error.

changeUserInfoFashion = function (id, dataToChange, res, callback) {
//var id = id;
_.forIn(dataToChange, function (value, key) {
key.toString();
console.log('I AM GOING TO UPDATE ' + key + " WITH " + value);
User.update(
{"_id": id},
//Here I need to 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 is

{
name: 'Baby',
age: 32
}

Answer

No need to iterate the object and update each field, you can use the $set operator as 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);
        }
    );    
};