I am new to NodeJS. I know there are a lot of questions about asynchronous NodeJS but I couldn't find exactly what I am looking for.
My problem is: I want to check if username and email already exist or not in my database. Two separate functions for username and email. Another function is for storing data to database.
I don't know to do this using asynchronous NodeJS pattern.
User.js (mongoose Schema)
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)
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 });
}
});
});
Please me help to solve this and please forgive if it sounds stupid.
via Big Guy
No comments:
Post a Comment