Mongodb, Update Collection Field If New Value Is Not Null

MongoDB, update collection field if new value is not null

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 )

MongoDB Query, update specific field if value is not null

I was struck at the same problem and solved by below solution

  let params= {
id: req.body.id, componentId: req.body.x, commands: req.body...,
}

;
for(let prop in params) if(!params[prop]) delete params[prop];//it will remove fields who are undefined or null

testCollection.findOneAndUpdate( {
_id: req.params.id
}

, params);

mongoose update only not nulled fields?

You can remove empty string properties from the object before save it.

const obj = {
name: "",
password: "98765432",
role: "Admin"
}

Object.keys(obj).forEach((k) => obj[k] == '' && delete obj[k]);

User.findByIdAndUpdate(req.user._id, obj)

The remove empty string properties function is taken from https://stackoverflow.com/a/38340730/9095807

or use the .pre('save') method of mongoose like this: https://stackoverflow.com/a/59916058/9095807

Don't overwrite value in mongo if new value is null

You can exclude the fields with falsy values, and send this filtered object to the update query.

  const { email, username, country } = req.body;

let filteredBody = {};

if (username) {
filteredBody["shared.username"] = username;
}

if (country) {
filteredBody["shared.country"] = country;
}

console.log(filteredBody);

const account = await userModel.findOneAndUpdate(
{ "shared.email": email },
filteredBody,
{
new: true
}
);

Test:

Let's say we have this existing user in our collection.

{
"_id": "5df24ed1ec018d37785c23bd",
"shared": {
"email": "user1@gmail.com",
"username": "user1",
"country": "USA"
}
}

When we send a request body like this:

{
"email": "user1@gmail.com",
"username": "",
"country": "England"
}

The username field will not be updated, but the country will be updated like this:

{
"shared": {
"email": "user1@gmail.com",
"username": "user1",
"country": "England"
},
"_id": "5df24ed1ec018d37785c23bd"
}

Mongo update all records with a field that's null

If the name field is not there try:

db.collection.update({"name": {"$exists": false}}, {"$set": {"name": "test"}})

$set will add a new field with the specified value, provided that the new field does not violate a type constraint.

If it is there and null, or does not have a value set:

db.collection.update({"name": null}, {"$set": {"name": "test"}})

You can combine both queries using $or as

db.collection.update(
{
"$or": [
{ "name": { "$exists": false } },
{ "name": null }
]
},
{ "$set": { "name": "test" } }
)

For MongoDB 3.2 and above, use updateMany() which updates multiple documents within the collection based on the filter:

db.collection.updateMany(
{
"$or": [
{ "name": { "$exists": false } },
{ "name": null }
]
},
{ "$set": { "name": "test" } }
)


Related Topics



Leave a reply



Submit