Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

448
Visualizações
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

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

two problems are here:

  1. if you want to use await your callback should be async:

    async () => { await ... }

  2. user in your code is referring to promises not use value came from promise. to do so you need to execute the query:

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

it is also better to use try catch to avoid your application breaks on bad request.

all in all:

async (req, res) => { // missing async

    const errors = validationResult(req)

    if (!errors.isEmpty()) {
        res.status(400).json({ errors: errors.array() }); // no need for return
    }
    try {
        let user = await User.findOne({ email: req.body.email}).exec(); // missing exec()

        if (user) {
            res.status(400).json({ error: "A user with this email already exist..."});
        }
        res.send("Successful request...👍");
    }
    catch (error) { console.log(error) }
})
about 4 years ago · Juan Pablo Isaza Relatório

0

Make the callback function asynchronous by using keyword

async (req, res) => {}
about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda