i am using node.js promise for validating either username exist in db or not

陌路散爱 提交于 2020-01-07 01:48:13

问题


i want to check either username exist in mongo db or not i want to do it by promise , i am new in node.js please help me to understand actual scenario thanks in advance.

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

回答1:


Mongoose is already promisified, so this will do:

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);
});

A Promise is asynchronous so only return the Promise and the caller will "wait" for it to be resolved and handle the errors.



来源:https://stackoverflow.com/questions/35008433/i-am-using-node-js-promise-for-validating-either-username-exist-in-db-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!