I'm beginner with mongoose and nodejs . I'm have two field unique in mongoose , how can I validate with it . Here is my code:
model
var userSchema = new Schema({
local:{
email:{type:String,required:true,unique:true},
username:{type:String,required:true,unique:true},
password:{type:String,required:true}
}
});
router
User.findOne({'local.email':req.body.email},function(err,user){
if(err) console.log(err)
if(user){
res.json({message:'Email already exists'})
next()
}
});
User.findOne({'local.username':req.body.username},function(err,user){
if(err) console.log(err)
if(user){
res.json({message:'Username already exists'})
next()
}
})
newUser = new User;
newUser.local.email = req.body.email;
newUser.local.username = req.body.username;
newUser.local.password=req.body.password;
newUser.save(function(err){
if(err) console.log(err)
res.json('Register Success');
});
Im try this code above , but unfortunately it not work . When first time , I try post unique email , It work , but after it , I getting error duplicate key error
. Cant set header after they are send
. I'm not sure with code in my router . Can anyone show me what should I do ?
via Thanh Tùng