Hi I’m learning nodejs with mysql. I have crated a method to post a name in database. But now I want to execute another method which first check if name does not exist then run post name method
NOTE My table only containes ‘nick_names’ column
Here is my route in router file router.post(‘/’, NickNamesController.createName)
Actual result-> I can post names here: Controller.js
exports.createName = (req, res) => {
const reqData = new NickNamesModel(req.body);
NickNamesModel.addNewName(reqData , (err, name) => {
if (err){
return res.status(400).send(err.code);
}
res.status(201).send({success: true, message: 'Name has been inserted successfully', data: name});
});
}
Expected: Controller.js Please have a look here This is what I want to achieve
exports.createName = (req, res) => {
const reqData = new NickNamesModel(req.body);
// first check if name exist or not?
const ifExist = NickNamesModel.getNameIfExist(reqData.nick_name, (err, name) => {
if(err){
return err.code;
}
return name;
})
// checking if ifExist has 1 then value already exist. If 0 then not exist
if(ifExist != 0) {
return res.status(400).send({success: false, message: Duplicate Name});
} else {
NickNamesModel.addNewName(reqData , (err, name) => {
if (err){
return res.status(400).send(err.code);
}
res.status(201).send({success: true, message: 'Name has been inserted successfully', data: name});
});
}
}
NickNamesModel.js
NickNamesModel.addNewName = (reqData, result) => {
dbConn.query('INSERT INTO nick_name_table SET ? ', reqData, (err, res) => {
if (err) {
console.log('Error while inserting name', err);
result(err, null);
}else {
console.log('Name inserted successfully');
result(null, res);
}
})
}
// Method to check if nick name already exist then return 1 else 0
NickNamesModel.getNameIfExist = (nick_name, result) => {
dbConn.query('SELECT EXISTS('SELECT station_name FROM stations SET WHERE station_name=? LIMIT 1)', nick_name, (err, res) => {
if (err){
console.log('Error while fetching stations', err);
result(null, err);
} else {
console.log('Stations fetched successfully');
result(null, res)
}
})
}