getting blank array when consoled logged out results in nodejs mysql - sql

I have this code where I want to check for existing email but I am not able to get the array of all the data containing matched row by SQL.
var email = req.body.email;
var fullname = req.body.fullname;
var userPassword = req.body.userPassword
const saltRounds = 10
let sql = 'SELECT * FROM registeredusers WHERE id = ?'
pool.query(sql, email, (err, results) => {
console.log(JSON.stringify(results))
if (err) {
return res.status(500).json({
message: 'Internal server error. Retry... '
})
}
else if (results === 1) {
return res.status(500).json({
message: 'Email already exist.',
res: results
})
}

just use
let sql = 'SELECT COUNT(*) AS cnt FROM registeredusers WHERE email = ?'
pool.query(sql, [req.body.email], (err, results) => {
if (err) {
return res.status(500).json({
message: 'Internal server error. Retry... '
})
}
else if (results[0].cnt > 0) {
return res.status(500).json({
message: 'Email already exist.',
})
}

Related

Cannot set Header after already being sent // node express

I am prompted with cannot set headers after they are already being set.
My code intercept for put method sent on the URL it then checks for missing id, after that checks if no field inputted is undefined it then perform try-catch method within which it updates for given id. If the id is not correct then it responds with an error.
My code is :
.put(async function (req, res){
console.log(req.body._id + " is id.")
const {_id, issue_title, issue_text, created_by, assigned_to, status_text, open} = req.body;
if(!_id){
res.json({error: "missing _id"})
}
const fields = {issue_title, issue_text, created_by, assigned_to, status_text, open}
const checkAllUndefined = Object.values(fields).every(val => (val == undefined || val == '')? true: false)
if(checkAllUndefined){
res.json({ error: 'no update field(s) sent', _id})
} else{
try{
await db.findOneAndUpdate({_id: new mongodb.ObjectID(_id)}, {$set:
{issue_title,issue_text,created_by, assigned_to, status_text, open,
updated_on: new Date()}}, {
new: true,
omitUndefined: true
})
res.json({ result: 'successfully updated', _id})
}catch(err){
res.json({ error: 'could not update', _id})
}
}
})
Your first If statement is returning the response if _id is undefined !
if(!_id){
res.json({error: "missing _id"})
}
After sending this response your next if block or its else block gets executed
which leads to sending another response which is not possible or allowed !, You have to nest if else block like this
put(async function (req, res) {
console.log(req.body._id + " is id.")
const {_id, issue_title, issue_text, created_by, assigned_to, status_text, open} = req.body;
if (!_id) {
res.json({error: "missing _id"})
} else {
if (checkAllUndefined) {
res.json({error: 'no update field(s) sent', _id})
} else {
try {
await db.findOneAndUpdate({_id: new mongodb.ObjectID(_id)}, {
$set:
{
issue_title, issue_text, created_by, assigned_to, status_text, open,
updated_on: new Date()
}
}, {
new: true,
omitUndefined: true
})
res.json({result: 'successfully updated', _id})
} catch (err) {
res.json({error: 'could not update', _id})
}
}
}
)
}
by doing this you are only sending response only once.

I am trying to use prepared statements to insert values given in an array

I am trying to INSERT values given in an array into my table, where each element of the array is a column in the table. Keep in mind this is for an API so the data is received through requests.
Here's the concerned parts in my code:
user.model.js:
User.create = function (newUser, result) {
console.log(Object.values(newUser));
dbConn.query("INSERT INTO user(user_fname, user_name, user_email, user_phone, user_is_admin) set ?", Object.values(newUser), function (err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
console.log(res.insertId);
result(null, res.insertId);
}
});};
user.controller.js:
exports.create = function (req, res) {
const new_user = new User(req.body);
console.log(req.body);
if (req.body.constructor === Object && Object.keys(req.body).length === 0) {
res.status(400).send({
error: true,
message: 'Please provide all required field'
});
} else {
console.log(new_user);
User.create(new_user, function (err, user) {
if (err) {
res.send(err);
}
res.json({
error: false,
message: "User added successfully!",
data: user
});
});
}};
In this last bit of code here is the output of the console.logs:
{
user_fname: 'toto',
user_name: 'titi',
user_email: 'who#where.how',
user_phone: '1010101010',
user_is_admin: 'false'
}
User {
fname: 'toto',
name: 'titi',
email: 'who#where.how',
phone: '1010101010',
is_admin: 'false'
}
[ 'toto', 'titi', 'who#where.how', '1010101010', 'false' ]
And last but not least here's the error message I get:
error: SqlError: (conn=357, no: 1064, SQLState: 42000) You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'set 'toto''
at line 1 sql: INSERT INTO user(user_fname, user_name, user_email,
user_phone, user_is_admin) set ? -
parameters:['toto','titi','who#where.how','1010101010','false']
I'm clear on the fact my syntax is wrong but I can't seem to find anything that works. Thank you for your time :)
Found the answer !
So as I thought my syntax was wrong, here's the correct way to do it:
User.create = function (newUser, result) {
console.log(Object.values(newUser));
dbConn.query("INSERT INTO user(user_fname, user_name, user_email, user_phone, user_is_admin) values(? , ? , ? , ? , ?)", Object.values(newUser), function (err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
console.log(res.insertId);
result(null, res.insertId);
}
});
};

Filter sql request with WHERE and ORDER express js API

I don't know why this syntax doesn't work, I just want to get back my data throw this little API;
when I delete the 'ORDER by points DESC', it works.
This is the code :
.get((req, res) => {
if (req.query.max != undefined && req.query.max > 0){
db.query('SELECT * FROM rank WHERE id_championship = ?', [req.params.id] 'ORDER by points DESC', (err, result) => {
if(err){
res.json(error(err.message))
}
else{
res.json(success(result.slice(0, req.query.max)))
}
})
}
Thanks for your help !
I have tried to do it like this but it still not working...
sql = "SELECT * FROM rank WHERE id_championship = " + req.params.id + "ORDER BY id DESC";
db.query(sql, (err, result) => {
if(err){
res.json(error('Fail database connection'))
}
else{
res.json(success(result))
}
})

Select For Update query from Node JS

Currently i use below code to select details from SQL for my Node JS server. Now i have a requirement where i want to use 'SELECT FOR UPDATE' and i am sure how to proceed with that?
pool.connect((err, db) => {
if(err) {
console.log("Failed connection to mysql");
errHandler(err);
}
let sql1 = 'select * from user where email = ? and role_number = ? ';
db.query( sql1 , [ email, role ], (err, result) => {
if(err) {
console.log("Error in checking existing email");
errHandler(err);
}
else {
console.log(result);
if( result.length > 0 ) {

SQL tedious add array as parameter

I'm running this SQL query with tedious.js using parameters:
var query = "select * from table_name where id in (#ids)";
request = new sql.Request(query, function(err, rowCount) {
if (err) {
}
});
request.on('row', function(columns) {
});
var id = [1, 2, 3];
request.addParameters('ids', TYPES.Int, id);
connection.execSql(request);
because I am looking for items that matches the ID provided with where ... in ... clause, I need to pass in an array. However, there is no TYPES.Array. How do I this properly?
for this query, i think you'll just have to manually build the entire sql string. the TYPES enum values are for the datatypes in the database, not in your JavaScript code.
//you can like this:
var userIds = result.map(function (el) {
return el.UserId;
}).join(',');
var params = [{
name: 'userIds',
type: TYPES.VarChar,
value: userIds,
options: null}];
var querySql = ['SELECT COUNT([MomentId]) FROM [T_Moment]',
'WHERE [RecordStatus] = ', sysConst.recordStatus.activation, " AND CHARINDEX(','+RTRIM([UserId])+',' , ','+ #userIds +',')>0 "].join(' ');
dbHelper.count(querySql, params, function (err, result) {
if (err) {
callback('error--');
} else {
callback(null, result);
}
});
Try creating the in clause parameters for query dynamically.
// create connection
let ids = [1, 2, 3];
let inClauseParamters = createInClauseParameters();
let query = `select * from table_name where id in (${inClauseParamters})`;
let request = new Request(query, (err, rowCount) => {
if (err) { /* handle error */ }
});
request.on('row', (columns) => { /* get row */});
request = addRequestParameters(ids, request);
connection.execSql(request);
function createInClauseParameters(values) {
return values.map((val, index) => `#Value${index}`).join(',');
}
function addRequestParameters(values, request) {
values.forEach((val, index) => {
request.addParameter(`Value${index}`, TYPES.VarChar, val);
});
return request;
}