Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
mongoose how to update properties in document only if they exist in request?

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));
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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. Which is in the fields NOT_ALLOWED variable will not be updated.

const NOT_ALLOWED = ['_id'] //Just the same field will update which are not in this variable
     Model.findById(id).then((docs) => {
        Object.keys(req.body).map((key) => {

            if (NOT_ALLOWED.indexOf(key) === -1) {
                docs[key] = req.body[key]
            }

        })
        return docs.save()
    })
        .then((result) => console.log("Updated Data", result))
        .catch((err) => res.send(err));
about 4 years ago · Juan Pablo Isaza Report

0

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));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!