await can only be used INSIDE a function that is declared with the async keyword.
async function doSomething() {
let result = await someMongoooseFunctionThatReturnsAPromise();
// use result here
}
await cannot be used outside an async function. That's what your error is telling you and it has nothing to do with mongoose at all. It has to do with the structure of YOUR code that is calling the mongoose function.
NOTE: Any node.js event driven code is ALREADY inside a function so to use await in that function, all you have to do is to add the async keyword to that containing function definition. If the caller of that function is not expecting any return result, then no further changes are required. If the caller of that funcition is expecting a return result, then you have to adapt the calling code to expect a promise to be returned from the async declared function.
It's also worth understanding that an async function ALWAYS returns a promise. While you may write it like regular sequential code:
async function doSomething() {
let result = await someMongoooseFunctionThatReturnsAPromise();
// use result here
result++;
return result;
}
This function is actually returning a promise and the resolved value of that promise will be the return value of the function. So, when you use an async function like this, you have to use the returned promise:
doSomething().then(finalResult => {
console.log(finalResult);
});
So, in your specific code, if you're going to use await, it needs to be inside an async function:
async function someFunc() {
const result = await User.findOne({email: email}).exec();
// now this will work and you can use result here
}
Alternatively, you can use .then() instead:
User.findOne({email: email}).exec().then(result => {
// process result here
// continue with other code that uses result here
});
NOTE: To handle errors when using async/await, you have two choices:
You can use traditional try/catch inside any async declared function and the try/catch will catch any rejected promises from await.
If you don't use try/catch and an await inside your function rejects, then the promise that the function itself returns will become rejected and the caller of your function will get the rejected promise.
So, it depends upon the situation. If you want to handle a rejection locally, then you must use try/catch around await (much like you would with .catch(). If you want the rejecting to bubble up to the caller so they will see the rejected promise, then you don't need the try/catch as the Javascript interpreter will automatically bubble a rejected await by rejecting the promise that the async function returns.