8

Mongoose's documentations affirms that method save returns a promise. I would like to save a user model in my database using this method. I do this like that :

save (user) {
    user.save((err, user) => {
        if (err) {
            return handleError(err);
        } else {
            console.log('The user ' + user.screenName + ' has been added.');
        }

        this.db.close();
    });
}

Note that user param is :

mongoose.model('User', this.userSchema);

I don't understand why the console.log below returns false :

console.log((userRepository.save(user) instanceof Promise));

And of course when I try to then() the promise I doesn't work.

Am I missing something ? I also tried to return the user.save(...) but it still did not work.

Thanks for reading my message and have nice day!

1 Answers1

16

First, your save(user) method doesn't currently return anything itself, so the result will always be undefined regardless of Mongoose' behavior:

console.log(typeof userRepository.save(user) === 'undefined'); // true

However, Mongoose generally makes you choose either callbacks or promises with each of its methods. The documentation isn't especially clear about this, beyond implying it through example snippets: Mongoose's documentation does now clarify this:

Returns:

  • «Promise,undefined» Returns undefined if used with callback or a Promise otherwise.

Callback:

product.sold = Date.now();
product.save(function (err, product) {
  if (err) ..
})

Promise:

product.save().then(function(product) {
   ...
});

In your case, if you want to return a Promise, then your save(user) method will also have to use and return them:

save (user) {
    return user.save()
        .then(user => console.log('The user ' + user.screenName + ' has been added.'))
        .catch(err => handleError(err))
        .finally(() => user.db.close());
}

(Note: regarding .finally())

Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • Thank you so much Jonathan Lonowski ! –  Mar 11 '18 at 09:07
  • Hi @JonathanLonowski how would you make the example above aync ? Would it be: `async save (user) { return await user.save() .then(user => console.log('The user ' + user.screenName + ' has been added.')) .catch(err => handleError(err)) .finally(() => user.db.close()); }` – O'Dane Brissett Sep 16 '19 at 18:01