MongoDB, update collection field if new value is not null

javascript, mongodb, node.js

Solution

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 )

Problem

I would update a collection setting the value only if the new values are not null. I have a code like this: ``` ... var userName = req.body.nome; var userSurname = req.body.cognome; var userAddress = req.body.indirizzo; collection.update( {_id:ObjectId(req.session.userID)}, {$set: { nome: userName, cognome: userSurname, indirizzo: userAddress }} ) ``` Is there an easy way for doing this? ANOTHER WAY: if I could take the value `req.body.*` from the placeholder of the form where I take the data, I could solve the problem.. but is this possible?

Original source

Related problems