【问题标题】:i am using node.js promise for validating either username exist in db or not我正在使用 node.js 承诺验证数据库中是否存在用户名
【发布时间】:2016-05-02 16:43:36
【问题描述】:

我想检查 mongo db 中是否存在用户名我想通过 promise 来做,我是 node.js 的新手,请帮助我了解实际情况提前谢谢。

var errorsArr = [];
var promise = username();
promise.then(function(data){
    errorsArr.push({"msg":"Username already been taken."});
},console.error);

username(function(err,data){
    User.findOne({"username":req.body.username},function(err,user) {
        if(err)
            return console.error(err);

        return user;
    });
});

console.log(errorsArr);

【问题讨论】:

  • 你有什么问题?
  • 它告诉我一个错误用户名函数未定义,我问我是否以正确的方式使用承诺?
  • 不,这不是正确的方法。在尝试使用它之前,您需要先创建一个 Promise。创建 Promise 的方式取决于您使用的 Promise 实现。你安装了哪个 promise npm 包?

标签: node.js mongodb mongoose synchronous


【解决方案1】:

Mongoose 已经被承诺了,所以可以这样做:

function findUser() {
  return User.findOne({ "username": req.body.username })
    .then(function(user) {
      if (user) {
        // user exists, you can throw an error if you want
        throw new Error('User already exists!');
      }

      // user doesn't exist, all is good in your case
    }, function(err) {
      // handle mongoose errors here if needed


      // rethrow an error so the caller knows about it
      throw new Error('Some Mongoose error happened!');
      // or throw err; if you want the caller to know exactly what happened
    });
}

findUser().then(function() {
  // user doesn't exist, do your stuff

}).catch(function(err) {
  // here, you'll have Mongoose errors or 'User already exists!' error
  console.log(err.message);
});

Promise 是异步的,因此只返回 Promise,调用者将“等待”它解决并处理错误。

【讨论】:

  • @user2377300 我在User.findOne() 之前忘记了return。现在应该可以工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
相关资源
最近更新 更多