Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB, update collection field if new value is not null

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?

like image 695
Nicola Avatar asked Feb 27 '14 14:02

Nicola


People also ask

Is it possible to update MongoDB field using value of another field?

Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.

How do I ignore NULL values in MongoDB?

Solution 1: In case preservation of all null values[] or null fields in the array itself is not necessary. Filter out the not null elements using $filter , the ( all null elements) array would be empty, filter that out from documents using $match then $sort on values .

How do I update a single field in MongoDB?

To update a single field or specific fields just use the $set operator. This will update a specific field of "citiName" by value "Jakarta Pusat" that defined by $set operator.


2 Answers

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 )
like image 190
Ivan.Srb Avatar answered Oct 21 '22 23:10

Ivan.Srb


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}

like image 31
Edward Newsome Avatar answered Oct 22 '22 00:10

Edward Newsome