Create and Save a Record of a Model - Model created & saved, but the tests time out!

I updated to the latest version of mongoose because in the latest version this function : “person.save(function(err, data) {})” no longer takes a call back, it sends a promise so it should be handle with a .then & a .catch, the model is created & saved, but the tests time out, can somebody tell me how to go around that ?
Here’s what I did in the createAndSavePerson function

const createAndSavePerson = (done) => {
  
  var mohamed = new Person({
    name:'mohamed',
    age:30,
    favoriteFoods:['pasta', 'lasagna']
  });
  mohamed.save().then(doc => {
    console.log('Document saved:', doc);
  })
  .catch(err => {
    console.error('Error saving document:', err);
  });
};

saved
timeout

I should also specify that Model.prototype.save didn’t work in the previous versions with the callback function, i kept having a deprecation error !

Somebody Help please ! :pray: :pray: :pray:

The tests inside server.js are using callbacks as well, in order to use a version of Mongoose where callbacks have been removed, you would need to update the tests as well.

I would suggest you use the initial dependencies provided to you by the boilerplate and use the expected callback syntax.

You can use the promise syntax, but you have to use a version of Mongoose that still accepts callbacks as well (so the tests in server.js will still work).


Just for completeness. When using promises it would look like this, remember you still have to call the done callback passed into the different functions that wraps the code, as that is used for the tests (the done callback is unrelated to Mongoose).

someDoc.save()
  .then(data => done(null, data))
  .catch(err => done(err))

Or

try {
  const data = await someDoc.save();
  done(null, data);
} catch (err) {
  done(err);
}
1 Like

Thanks @lasjorg, I ended up downgrading to version 8.11.15, it turns out the tests pass despite the deprecation warning, but you’re right, i completely forgot about the dones earlier :pray: