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?
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.
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 .
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.
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 )
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With