await not working on mongoose model .findOne({email : req.body.email})

I am new to express and mongodb… I am trying to use user.findOne({email}) function returns the user with email with await keyword but the node js throws error saying

let user = await User.findOne({ email: req.body.email });
           ^^^^^

SyntaxError: await is only valid in async function

const express = require('express');
const User = require("../models/user");
const {body, validationResult} = require("express-validator");
const router = express.Router();

// Listening the request at assigned route
router.post('/', [
    // Validation array
    body("name", "Enter name").isLength({ min: 5 }),
    body("email", "Enter valid email").isEmail(),
    body("password", "password must not be less than 5").isLength({ min: 5 })

] ,

(req, res) => {

    // Errors in a single json...
    const errors = validationResult(req)

    // If there error return the error json...
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }

    // Check if there any user with same email...
    let user = await User.findOne({ email: req.body.email });

    if (user) {
        return res.status(400).json({ error: "A user with this email already exist..."});
    }

    // Create user...
    // user = await User.create({
    //     name : req.body.name,
    //     email : req.body.email,
    //     password : req.body.password
    // })

    // res.json(user)
    res.send("Successful request...👍");
    
})

module.exports = router

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use await only in async functions.
You can then just write:
(req, res) => {
like
async (req, res) => {.

The other way would be to not use async (but that’d work too), is to use a callback function:
User.findOne({ email: req.body.email }).then((user)=>{ /* Your logic here */})

In general, I prefer to not mix up async/callbacks, so I stick to only use async or only use callbacks 🙂

Method 2

Make the callback function asynchronous by using keyword

async (req, res) => {}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x