Home > Software engineering >  mongoose update only not nulled fields?
mongoose update only not nulled fields?

Time:10-26

If I want to update already created collection, I want only save not null fields.

Example- Suppose I create a collection Here User-

name: "Siam Ahnaf"
password: "12345678"
role: "user"

This is created collection. Then I want to update it. For updating I get this object from frontend application like this-

{name: "",
password: "98765432"
role: "Admin"}

Here I can see name is empty that I get from frontend application. When I update it with

User.findByIdAndUpdate(req.user._id, {...input})

It update the collection with this empty name. After updating my collection is like this-

name: ""
password: "98765432"
role: "Admin"

But I want when name is empty then it will not save this empty valuse. It remain previous value. How can I do that?

CodePudding user response:

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

  • Related