Callbacks with Mongoose / Node js

Upon completing the Mongoose/MongoDB - Create and Save a Record of a Model challenge I was wondering about something when it came to saving a document.

In the docs, it uses the await keyword with document.save()

But with the FCC solution provided when clicking the “Tip” button it doesn’t contain the await keyword. I was curious as to why?

Further looking at document.save() it appears to only accept an object and not a callback?

Then the challenges mention to use a callback that follows Node convention. I’m confused as to what style I should be using for future projects?

const createAndSavePerson = function(done) {
  var janeFonda = new Person({name: "Jane Fonda", age: 84, favoriteFoods: ["eggs", "fish", "fresh fruit"]});

  janeFonda.save(function(err, data) {
    if (err) return console.error(err);
    done(null, data)
  });
};

I may not be the best person to explain this, so anyone correct me if i explain it poorly:

As of recently, mongoose functions like find() or save() no longer accept a callback.
Now you have to do something like this:

doc.save()
   .then(() => {
       // whatever you need if it is successful
   })
   .catch((err)=> {
       console.log(err);
   })

The calling of a function like doc.save() returns a promise, and you can deal with this promise by using a method like .then() (my example) or await. There is a lesson in the javascript curriculum to practice with asynchronous programming.

In summary, await is basically pausing the execution of its surrounding async function until that promise is settled (fulfilled or rejected).

Hope I didnt make you more confused :rofl: