freeCodeCamp Challenge Guide: Perform New Updates on a Document Using model.findOneAndUpdate()

Perform New Updates on a Document Using model.findOneAndUpdate()


Relevant Links


Hints

Hint 1

Remember to use model.findOneAndUpdate() .

Hint 2

findOneAndUpdate uses ( conditions , update , options , callback ) as arguments.

Hint 3

Don’t forget the use new option to return the updated document.


Solutions

Solution 1 (Click to Show/Hide)
const findAndUpdate = (personName, done) => {
  const ageToSet = 20;

  Person.findOneAndUpdate({name: personName}, {age: ageToSet}, {new: true}, (err, updatedDoc) => {
    if(err) return console.log(err);
    done(null, updatedDoc);
  })
};

Code Explanation

  • In Mongoosejs, findOneAndUpdate returns the new document if the new property is set to true.

Relevant Links

2 Likes