我正在使用node.js承诺来验证数据库中是否存在用户名 [英] i am using node.js promise for validating either username exist in db or not
本文介绍了我正在使用node.js承诺来验证数据库中是否存在用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查mongo数据库中是否存在用户名,或者我想通过诺言做到这一点,所以我是node.js的新用户,请帮助我提前了解实际情况.
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);
推荐答案
猫鼬已经存在,所以可以这样做:
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);
});
Promise是异步的,因此仅返回Promise,调用者将等待"它被解决并处理错误.
A Promise is asynchronous so only return the Promise and the caller will "wait" for it to be resolved and handle the errors.
这篇关于我正在使用node.js承诺来验证数据库中是否存在用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文