【发布时间】:2019-01-03 03:37:25
【问题描述】:
所以我正在尝试创建一个函数来检查用户是否存在于数据库中,如果不存在则将其导入数据库。我正在尝试使用 await 功能,以便在继续之前等待功能完成。
const doesUserExist = (id) => {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db('db');
var users = dbo.collection('user');
return new Promise(function(resolve, reject) {
users.findOne({'id': id}, function (err, user) {
if (err) throw err;
console.log('User: ', user);
if (user === null) {
resolve(false);
} else {
resolve(true);
}
});
});
});
}
const userLogin = async (user) => { // User login function
var id = String(user.id);
// Check if the user exists
var doesExist = await doesUserExist(id);
console.log(doesExist);
if(doesExist===undefined){
console.log('ERROR: Exist is empty');
return;
}
if(doesExist===false){
console.log(`User with the id ${id} does not exist.`);
addUser(user);
} else {
console.log(`User with the id ${id} does exist.`);
}
}
【问题讨论】:
标签: node.js mongodb express asynchronous mean