【发布时间】:2017-10-23 07:49:58
【问题描述】:
我是 NodeJS 的新手。我知道有很多关于异步 NodeJS 的问题,但我找不到我正在寻找的确切内容。
我的问题是: 我想检查用户名和电子邮件是否已经存在于我的数据库中。用户名和电子邮件的两个独立功能。另一个功能是将数据存储到数据库中。
我不知道如何使用异步 NodeJS 模式来做到这一点。
User.js(猫鼬模式)
const mongoose = require('mongoose');
var userSchema = mongoose.Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
email: { type: String, required: true, unique: true},
aiub_id: String,
});
const Users = module.exports = mongoose.model('User', userSchema);
module.exports.addUser = function (user, callback) {
user.save(callback);
}
module.exports.usernameExist = function (givenUsername, callback) {
Users.find({ username: givenUsername }, callback);
}
module.exports.emailExist = function (givenEmail, callback) {
Users.find({ username: givenEmail}, callback);
}
index.js(路由)
route.post('/signup', function(req, res){
// GRAB USER INFO FROM HTML FORM
var newUser = new User({
name : req.body.tfullName,
username : req.body.tusername,
password : req.body.tpassword,
email : req.body.temail,
aiub_id : req.body.tuserID
});
// This block send 200 if username doesn't exist
User.usernameExist(newUser.username, function (err, result){
if(err){
throw err;
}
if(result.length <= 0){
res.send({status : 200 });
}else{
res.send({status : 100 });
}
});
});
请帮我解决这个问题,如果这听起来很愚蠢,请原谅。
【问题讨论】:
-
您可以在此处使用
$or运行单个查询。这样您就无需担心链接回调,而且它的开销多 更少且速度更快。或者,您甚至可以接受返回的“重复错误”相当于确实存在一个唯一属性这一事实,然后要求用户再试一次。
标签: javascript node.js mongodb asynchronous