Home > Mobile >  mongoose how to update properties in document only if they exist in request?
mongoose how to update properties in document only if they exist in request?

Time:02-22

In order to update a document i usually do as such...

  Model.findById(id)
.then((doc) => {
  doc.fName = req.body.fName
    ? req.body.fName
    : doc.fName;
  doc.lName = req.body.lName 
  ? req.body.lName
  : doc.lName
  return doc.save();
})
.then((result) => res.send(" Succesfully updated ! New data: "   result))
.catch((err) => res.send(err));

..which checks if the field actually exists in the body request,otherwise it just passes the previous value.

Is there a way to just provide the fields in the request and let it do the check for itself so if a field does not exist,it will not delete it ? like so...

  Model.someMethod(id)
.then((doc) => {
  doc.fName = req.body.fName
  doc.lName = req.body.lName
  return doc.save();
})
.then((result) => res.send(" Succesfully updated ! New data: "   result))
.catch((err) => res.send(err));

CodePudding user response:

Using it in this way will only update the same field that you enter in the req.body.Other fields will be as it is.

 Model.findById(id).then((docs) => {
            Object.keys(req.body).map((key) => {
                docs[key] = req.body[key]
            })
            return docs.save()
        })
    .then((result) => console.log("Updated Data",result))
        .catch((err) => res.send(err));

CodePudding user response:

You can do that with one update query. First, you can construct the update config based on all the properties from the req.body. Then, just pass that update config to the update query. You can also pass { new: true } as third config to update query, so the updated document will be returned.

let update = {};
if (req.body.fName) update.fName = req.body.fName;
if (req.body.lName) update.lName = req.body.lName;

Model.findByIdAndUpdate(id, update, { new: true })
  .then((result) => res.send(" Succesfully updated ! New data: "   result))
  .catch((err) => res.send(err));
  • Related