Model.findById() in Mongoose - Async/await

Viewed 329

The docs say that the function findById() returns a Query.

In that doc you can see an example where we can use async/await in this way:

await Adventure.findById(id, 'name length').exec();

How is that possible that we can use async/await for a function that does not return a promise?

2 Answers

From the mongoose documentation we have:

Mongoose async operations, like .save() and queries, return thenables. This means that you can do things like MyModel.findOne({}).then() and await MyModel.findOne({}).exec() if you're using async/await.

You can find the return type of specific operations in the api docs You can also read more about promises in Mongoose.

And actually Model.findById() calls Model.findOne as the doc says:

This function triggers the following middleware.

  • findOne()

So I found the answer.

findById() returns a Query.

The type Query has a function called exec(). That is the function that actually returns the promise.

That is why we can use async/await.

Related