Reputation: 1742
I've written the code for registration in nodejs following is my code. I want to check whether the email already exist in db.If so then show error in client side.I'm using react native as front end.Following is my code.
users.post('/registration', function(req,res){
var today = new Date();
var appData = {
"error" :"1",
"data" : "",
"userData" :"",
};
var userData = {
"pwd" : req.body.password,
"phone_no" : req.body.contact,
"user_name": "" ,
"status" : 1,
"date" : today,
}
database.connection.getConnection(function(err, connection){
if(err){
appData["error"] =1;
appData["data"] = "Internal Server Error";
res.status(500).json(appData);
} else{
connection.query("INSERT INTO user_registration SET ?" ,userData, function(err,result,fields){
var phone = userData.phone_no;
connection.query("SELECT user_id from user_registration WHERE phone_no=?", [phone], function(err,result,fields){
if(!err){
appData.error= 0;
appData["data"] = "User registered Successfully";
appData["userData"] = userData;
appData["user_id"] =result[0].user_id;
let token = jwt.sign(result[0], process.env.SECRET_KEY);
appData["token"] =token;
res.status(201).json(appData);
} else{
appData["data"] = "Error Occured";
res.status(400).json(appData);
}
console.log(appData);
});
});
connection.release();
}
});
});
Upvotes: 1
Views: 5522
Reputation: 11
I am using MySQL with express js and this worked for me. if it helps anyone
const user = await Users.findAll({
where: {
email: req.body.email,
},
});
if (user[0]) {
return res.status(400).json({ msg: "Email already exist" });
}
Upvotes: 0
Reputation: 4533
Try this way .. Before insert data you have to check email exist or not
connection.query("SELECT COUNT(*) AS cnt FROM tableName WHERE email = ? " ,
body.email , function(err , data){
if(err){
console.log(err);
}
else{
if(data[0].cnt > 0){
// Already exist
}else{
connection.query("INSERT INTO ..." , function(err , insert){
if(err){
// retunn error
}else{
// return success , user will insert
}
})
}
}
})
Upvotes: 4