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
Angular:How to Add/Remove Files in the Angular
Calculating Sum of Checked Checkboxes
New Line in Paragraph When Enter Is Pressed in Textarea
Why Does Prettier Not Format Code in VS Code
Angular:Onclick on HTML Element According to Its Class
Bootstrap 4 Navbar-Toggler-Icon Does Not Appear
How to Push Value Pair into Object Using Method
How to Separate an Integer into Separate Digits in an Array in JavaScript
React Use State to Show Otherwise Hide
How to Call the Same Method for Different Elements With Different Ids
Enabling/Disabling Inputs Based on Checkbox Activity
How to Change Background Color of a Row on Checkbox Selection
Jquery Change Event Called Two Times
How to Avoid Scientific Notation for Large Numbers in JavaScript
How to Parse Through Local Json File in React Js