【问题标题】:await not working on mongoose model .findOne({email : req.body.email})等待不适用于猫鼬模型 .findOne({email : req.body.email})
【发布时间】:2022-06-25 11:45:51
【问题描述】:

我是 express 和 mongodb 的新手...我正在尝试使用 user.findOne({email}) 函数返回带有 await 关键字的电子邮件的用户,但节点 js 抛出错误提示

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

SyntaxError: await 仅在异步函数中有效

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

【问题讨论】:

  • 错误信息说的是?

标签: javascript node.js mongodb mongoose-schema


【解决方案1】:

您只能在异步函数中使用 await。 然后你可以写: (req, res) => { 喜欢 async (req, res) => {.

另一种方法是不使用异步(但这也可以),是使用回调函数: User.findOne({ email: req.body.email }).then((user)=>{ /* Your logic here */})

一般来说,我不喜欢混淆异步/回调,所以我坚持只使用异步或只使用回调:)

【讨论】:

    【解决方案2】:

    使用关键字使回调函数异步

    async (req, res) => {}
    

    【讨论】:

      【解决方案3】:

      这里有两个问题:

      1. 如果你想使用await,你的回调应该是async

        async () => { await ... }

      2. user 在您的代码中指的是诺言,而不是来自诺言的使用价值。为此,您需要执行查询:

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

      总之:

      async (req, res) => { // missing async
      
          const errors = validationResult(req)
      
          if (!errors.isEmpty()) {
              res.status(400).json({ errors: errors.array() }); // no need for return
          }
          let user = await User.findOne({ email: req.body.email }).exec(); // missing exec()
      
          if (user) {
              return res.status(400).json({ error: "A user with this email already exist..."});
          }
          res.send("Successful request...?");
          
      })
      

      【讨论】:

        猜你喜欢
        • 2021-06-18
        • 2019-05-10
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        • 2018-08-30
        • 2019-03-20
        • 2016-09-18
        相关资源
        最近更新 更多