简体   繁体   中英

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?

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) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM