私はNodeJSを初めて使用しています。私は、非同期NodeJSに関する多くの質問があることを知っていますが、私が探しているものを正確に見つけることができませんでした。私の機能をNodeJSで非同期に実行
私の問題は: ユーザー名と電子メールが既に存在するかどうかをデータベースから確認したいのですが。ユーザー名と電子メールの2つの機能別の機能は、データベースにデータを格納する機能です。
非同期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'を使用して1つのクエリを実行できます。次に、コールバックの連鎖を心配する必要はありません。**オーバーヘッドが少なく、高速です。あるいは、重複エラーが実際に存在するという事実が返されたことを受け入れるだけで、ユーザーに再度試してもらうように促すこともできます。 –