user3711521 user3711521 - 4 months ago 45
Node.js Question

Mongoose Model.update with dynamic field name

I'mtrying to pass field name as variable , here is what I tried but it's not working :

var update={};
update[req.body.field]=req.body.value;
Model.update(
{"email":req.user.email},
{$set:{update}},
function (err,success) {
if(err) return handleError(err);
}
)


req.body.field contains the name of the field defined in the Model schema and req.body.value is the value I want to update with

Answer

You don't need update to be in braces, since it is already an object. Try:

var update={};
update[req.body.field]=req.body.value;
Model.update(
    {"email":req.user.email},
    {$set:update},
    function (err,success) {
        if(err) return handleError(err);
    }
)