MongoDB, update collection field if new value is not null

Are you not just asking to pass in all the fields that you posted? Why not do this then?

(And basically just a cut and paste of your code):

collection.update(
    {_id: ObjectId(req.session.userID)},
    {$set: req.body }
)

Then whatever content you posted as fields is set within your update.

Note that use of set will only overwrite, or add new fields. If you just want to replace the whole document, then remove the whole {$set: (..) } notation and just pass in req body as it's a valild object.


You can use lodash like this other question: https://stackoverflow.com/a/33432857/4777292

_.pickBy({ a: null, b: 1, c: undefined }, _.identity);

would be

{b:1}


You could try something like this:

var objForUpdate = {};

if (req.body.nome) objForUpdate.nome = req.body.nome;
if (req.body.cognome) objForUpdate.cognome = req.body.cognome;
if (req.body.indirizzo) objForUpdate.indirizzo = req.body.indirizzo;

//before edit- There is no need for creating a new variable
//var setObj = { $set: objForUpdate }

objForUpdate = { $set: objForUpdate }

collection.update({_id:ObjectId(req.session.userID)}, objForUpdate )