【问题标题】:Mongoose find() callback not actually being calledMongoose find() 回调实际上没有被调用
【发布时间】:2019-06-04 20:04:22
【问题描述】:

我是 Mongoose 的新手,也使用 async/await。现在我有一个 Mongoose 模式,带有一个静态方法,如下所示:

const userSchema = new Schema({
    username: String,
    pass: String
});


userSchema.statics.checkExist = async function(username){
    return await this.findOne({username: username}, function(err, res){
        if(err){
            return err;
        }
        if(res){
            return true;
        }
        else{
            return false;
        }
    })
}

静态方法checkExist() 应该接受用户名,并检查是否已经存在具有相同用户名的文档。如果是,它应该返回 true,否则返回 false。我在我的 NodeJS/Express 服务器中使用它,如下所示:

router.post('/auth/login', async (req, res) =>{
    let username = req.body.username;

    let existBool = await UserModel.checkExist(username);

    console.log(existBool);
    res.send({'hash': existBool});
});

我希望 existBool 是真/假布尔值。相反,checkExist() 似乎根本没有调用回调函数。相反,它返回findOne() 的结果,这是一个具有匹配用户名字段的对象。我在这里做错了什么?

【问题讨论】:

    标签: node.js mongoose promise async-await


    【解决方案1】:

    您正在将回调与使用承诺的async/await 混合。您还误解了回调的工作方式; await的结果不是回调的返回值,而是findOne()的返回值。

    await 用于保持直到异步函数返回一个承诺,然后它将该承诺“解包”到一个变量中。如果findOne() 方法支持promise,则根本不应该使用回调。

    let result = await this.findOne({username: username})
    

    async/await 如此强大的原因是因为它消除了对.then() 承诺语法的需求,并允许您再次编写顺序代码,但让它处理异步行为。它让您可以使用循环,最重要的是,让您可以使用try/catch 语句再次处理错误。

    try {
      let result = await this.findOne({username: username})
    } catch(ex) {
      // handle exception here
    }
    

    【讨论】:

      【解决方案2】:

      这是架构

      const mongoose = require('mongoose');
      
      var userSchema = new mongoose.Schema({
          _id: mongoose.Schema.Types.ObjectId,
          username: {
              type: String,
              required: true,
              unique: true
          },
          password: {
              type: String,
              required: true
          }
      }, {
              timestamps: { createdAt: true, updatedAt: true },
              collection: 'users'
          });
      
      module.exports = mongoose.model("User", userSchema);
      

      Router端点在下方

      // API endpoint to insert new user.
      router.post('/insertUser', function (req, res, next) {
          let request = req.body;
          let userSchema = new UserModel({
              _id: new mongoose.Types.ObjectId(),
              username: request.username,
              password: request.password
          }); `enter code here`
      
          if (!userSchema.username) {
              res.status(200).json({ success: false, msg: 'Username can\'t be empty' });
          } else if (!userSchema.password) {
              res.status(200).json({ success: false, msg: 'Password can\'t be empty' });
          } else {
              // If username is not unique in schema do check this...
              UserModel.findOne({ username: userSchema.username }).exec()
                  .then(result => {
                      if (result == null) {
                          //Here the User is added
                          userSchema.save().then(result => {
                              res.status(200).json({ success: true, msg: 'User Added' });
                          }).catch(exception => {
                              console.log(exception);
                              res.status(200).json({ success: false, msg: 'Something went wrong' });
                          });
                      } else {
                          res.status(200).json({ success: false, msg: 'Username already taken' });
                      }
                  }).catch(exception => {
                      console.log(exception);
                      res.status(200).json({ success: false, msg: 'Something went wrong' });
                  });
          }
      
      });
      

      【讨论】:

        猜你喜欢
        • 2015-03-01
        • 2017-05-08
        • 2016-01-08
        • 2020-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多