Rob Monhemius
Rob Monhemius

Reputation: 5144

Why is mongoose find method not async?

Old code with promises

I have some old code using mongoose. It fetches some information from the database. AccountViewPermission is a schema. All good. I am accessing it with a .then which makes it behave like a Promise.

AccountViewPermission.find({ requested_by: request.body.credentials.character.id})
.then( permissions => {
  response.status(200).json(permissions)
})

Documentation mentions await capability

According to the documentation I should also be able to use asyn/await:

Mongoose queries are not promises. They have a .then() function for co and async/await as a convenience. However, unlike promises, calling a query's .then() can execute the query multiple times.

But using await throws an error

So I started writing this code with an await instead of a (wannabe) promise.

const permissions = await AccountViewPermission.find({ requested_by: request.body.credentials.character.id})
response.status(200).json(permissions)

However now node.js throws me an error: SyntaxError: await is only valid in async function. Which is true, but the docs say mongoose should still be able to use await.

How can I use the await syntax in this scenario?

Upvotes: 1

Views: 1943

Answers (1)

Aaron
Aaron

Reputation: 1727

As stated in the official docs "The await operator is used to wait for a Promise. It can only be used inside an async function." Docs: await-operator

Mongoose cant change the way javascript deals with async / await keywords. if you need follow-up information check the docs.

To make your code work you HAVE to wrap it inside a async function. There is no way around this.

async function doSomething() {
  const permissions = await AccountViewPermission.find({
    requested_by: request.body.credentials.character.id
  })
  response.status(200).json(permissions)
}

Upvotes: 3

Related Questions