MongoDB timing out when using model.findOneAndUpdate()

I’m working through the API & Microservices course and have got stuck trying to implement Person.findOneAndUpdate().
Whenever I run my code I get an error saying the test has timed out, and I’m not sure what I’ve done wrong.

The error:

// running tests
findOneAndUpdate an item should succeed (Test timed out)
// tests completed

My code so far:
I’ve been trying to follow the syntax suggested by the course, with all these nested callbacks and whatnot, and it’s worked completely fine up to this lesson. Chances are I’ve just made a silly mistake but I would really appreciate someone helping me out :slight_smile:

var findAndUpdate = function(personName, done) {
  var ageToSet = 20;
  Person.findOneAndUpdate(
    {name: personName},
    function(err, person) {
      if (err) return console.log(err);
      person.age = ageToSet;
      person.save((err, data) => {
        if (err) return console.log(err);
        done(null, person);
      })
    },
    {new: true}
  );
};

My browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0.

Challenge: MongoDB and Mongoose - Perform New Updates on a Document Using model.findOneAndUpdate()

Link to the challenge:

Hi, i am able to find your post because i searched it :grinning: (i am currently on working on this too). However i am able to get this test to pass by checking the Mongoose documentation. findOneAndUpdate() isn’t a classical method like the ones you are been using up to this challenge that’s why your code didn’t work. It takes four argument instead of 2 which are
findOneAndUpdate(conditions, update, options, callback)
and this arguments are optional based on what you want to do but for your case it should be


Person.findOneAndUpdate(
  { name: personName },
  { age: ageToSet },
  { new: true },
  function(err, data) {
    if (err) done(err);
    done(null, data);
  }
);

I hope this helps :smile:

1 Like

I tried this one and it worked out for me
var findAndUpdate = function(personName, done) {
var ageToSet = 20;
Person.findOneAndUpdate(
{name: personName},
{age:ageToSet},
{new: true},function(err,data){
if(err)return console.log(err);
done(null,data);
}
);
};