Fetch data express js - javascript

Right now I am getting data from mysql in res.send but if I want to display two different records in different position (two different <ul>) then how can I do this?
Here is my code
connection.query('SELECT * FROM test',
function (err, rows, fields) {
if (err) throw err
var id =rows[0].number;
if (id != req.body.id) {
res.send("wrong accept");
} else {
var test = rows;
var length = Object.keys(rows).length;
const numberList = rows.map(row => row.number)
const numberLists = rows.map(row => row.test)
res.send({ number: numberList, text: numberLists })
}
})

Related

How to update the variable from the result of connection.query function?

I am creating a simple web application and am stuck on a simple problem. I want to update the temp variable from the results of my inner query. I know that connection.query might take some time, so the rest of the code is executed first. In the final response, I am not getting the value of temp.user_image and temp.user_name.
router.get("/home/getArticles", (req, res) => {
var select_query = "SELECT * FROM `articles` WHERE 1";
connection.query(select_query, async (err, result) => {
if (err) {
return res.status(500).json({ message: "Error while processing your request" });
}
var final_data = [];
for (var i = 0; i < result.length; i++) {
var temp = {};
let current_user_id = result[i].user_id;
var select_query = "SELECT * FROM `users` WHERE `user_id`=" + mysql.escape(current_user_id) + "";
connection.query(select_query, (err, innerResult) => {
if (err) throw err;
temp.user_name = innerResult[0].user_name;
temp.user_image = innerResult[0].user_profile_image;
});
temp.title = result[i].title;
temp.body = result[i].detail;
final_data.push(temp);
}
return res.status(200).json({ data: final_data });
})
})
There are 2 problems in your code:
The server response before the second query finish - which you've already known.
This way of querying relationship will result in extremely bad performance known as N+1 query problem
For an example, we can use SQL JOIN clause for querying relationship:
router.get("/home/getArticles", (req, res) => {
var select_query = "SELECT articles.*, users.user_name, users.user_profile_image AS user_image FROM `articles` LEFT JOIN `users` ON `articles`.`user_id` = `users`.`id` WHERE 1";
connection.query(select_query, async (err, result) => {
if (err) {
return res.status(500).json({ message: "Error while processing your request" });
}
return res.status(200).json({ data: result });
})
})

Returning values within an array if it contains a value

I have an array that I am trying to return but only return certain rows within that array if the column Free_Agent is populated (or I could do if Years_Kept is greater than or equal to 2).
Here is my code where I have been able to successfully return the values of the array by a console log. Everything I try when I either try to do a forEach or pull the filtered data via a filter view I have set up (363219995) will not work.
async function gsrun(cl){
const gsapi = google.sheets({version:'v4', auth: cl });
gsapi.spreadsheets.values.get({
spreadsheetId: "11e5nFk50pDztDLngwTSmossJaNXNAGOaLqaGDEwrbQM",
range: 'Keepers!C1:F',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
rows.map((row) => {
console.log(`${row[0]}, ${row[1]}, ${row[2]}, ${row[3]}`);
});
} else {
console.log('No data found.');
}
})
};
Terminal Screenshot of mapped Array
Can anybody please help a newbie? I've been teaching myself and watching videos and reading everything I can, I just can't seem to grasp it.
You have to filter the values (rows) arrays to check if there is a value.
async function gsrun(cl){
const gsapi = google.sheets({version:'v4', auth: cl });
gsapi.spreadsheets.values.get({
spreadsheetId: "11e5nFk50pDztDLngwTSmossJaNXNAGOaLqaGDEwrbQM",
range: 'Keepers!C1:F',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
const cells = rows.filter(cell => cell[3])
cells.map((cell) => {
console.log(`${cell[0]}, ${cell[1]}, ${cell[2]}, ${cell[3]}`);
});
} else {
console.log('No data found.');
}
})
};
Just adding to #ArthurCosta's answer, based on the second condition you provided.
async function gsrun(cl){
const gsapi = google.sheets({version:'v4', auth: cl });
gsapi.spreadsheets.values.get({
spreadsheetId: "11e5nFk50pDztDLngwTSmossJaNXNAGOaLqaGDEwrbQM",
range: 'Keepers!C1:F',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
const cells = rows.filter(cell => cell[3] || (parseInt(cell[2]) >= 2))
cells.map((cell) => {
console.log(`${cell[0]}, ${cell[1]}, ${cell[2]}, ${cell[3]}`);
});
} else {
console.log('No data found.');
}
})
};

Trouble setting a players ID and Username through callback

With an HTML5 game I am developing at the moment, I get the player's username and ID through a token sent in by the client which are all stored in a database. Everything was working perfectly up until I had to actually set the values for the player.
I've been searching all over the internet for similar problems that I am facing, and have come up with nothing. I am not sure if this is a variable scope problem or if I am taking the wrong approach to doing this.
Anyways, here's both the socket.player and getUserSession function
var newUserID;
var newUsersName;
socket.player = {
id: newUserID,
x: randomInt(100,400),
y: randomInt(100,400),
username: newUsersName
}
function getUserSession(sessionKey, callback){
var sql = "SELECT * FROM game_sessions WHERE unique_key=? AND still_active=?";
var stillActive = 1;
var returnData = [];
db.query(sql, [sessionKey, stillActive], function(err, result){
if (err){
throw err;
}
var numFound = result.length;
if (numFound == 1) {
//session was found
var userID = result[0].user_id;
returnData.push(result[0].user_id);
var sql2 = "SELECT * FROM users WHERE id=?";
db.query(sql2, [userID], function(err, result){
if (err){
throw err;
}
var uName = result[0].username;
returnData.push(result[0].username);
return callback(returnData);
});
}
});
}
And the callback function:
getUserSession(data.token, function(result){
newUserID = result[0];
newUsersName = result[1];
socket.broadcast.emit('newclient',socket.player);
});
I would do something like this:
function sqlQuery(sql, params) {
return new Promise((resolve, reject) => {
db.query(sql, params, function(err, result) {
if (err) {
return reject(err);
}
return resolve(result);
});
});
}
function getUserSession(sessionKey, callback){
const sql = "SELECT * FROM game_sessions WHERE unique_key=? AND still_active=?";
const stillActive = 1;
let returnData = [];
try {
return sqlQuery(sql, [sessionKey, stillActive])
.then(result => {
if (result.length === 1) {
//session was found
const userID = result[0].user_id;
returnData.push(result[0].user_id);
const sql2 = "SELECT * FROM users WHERE id=?";
return sqlQuery(sql2, [userID])
.then(result => {
const uName = result[0].username;
returnData.push(result[0].username);
return callback(returnData);
})
}
})
} catch (err) {
//handle err
}
}
Edit: if the callback function being passed in is an aync function, you'll probably need to modify the above snippet to await it.

Node.js: Map function doesn't work on query from PostgreSQL

I'm creating my first app using Node.js and PostgreSQL.
This app connect's to db and return record to browser in JSON format, its work perfectly till i try to use map function to formating properties.
When i use map it return an error:
TypeError: rows.map is not a function
This is my code.
app.get('/car/:id', (req, res) => {
const car_id = req.params.id;
const queryString = `SELECT * FROM cars WHERE car_id= ${car_id}`;
client.query(queryString, (err, rows, fields) => {
if (err) {
console.log(err.stack);
res.sendStatus(500);
res.end();
} else {
const car = rows.map((row) => {
return {"Car_ID": row.car_id}
});
res.json(car);
console.log(rows.rows);
}
});
It should be result.rows not just rows
According to this - https://node-postgres.com/api/result
app.get('/car/:id', (req, res) => {
const car_id = req.params.id;
const queryString = `SELECT * FROM cars WHERE car_id= ${car_id}`;
client.query(queryString, (err, result, fields) => {
if (err) {
console.log(err.stack);
res.sendStatus(500);
res.end();
} else {
const car = result.rows.map((row) => {
return {"Car_ID": row.car_id}
});
res.json(car);
console.log(result.rows);
}
});

Throwing a error message if the user id not exist in mysql using node.js

Right now, in my code, if I input an id, which is not present in the database, it's showing empty array on the console. But rather than empty array, I want to print an error message. This is my code.
server.on('request', (req, res) => {
case '/get':
req.on('end', () => {
let id = reqUrl.query.id;
let sql = `Select * from students WHERE id= ${id} `;
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
})
res.end('');
});
this console.log(result) shows [ RowDataPacket { id: 3, name: 'v', grade: 1 } ] if an id exists but if an id is not present then it shows [ ]. But instead of [ ], i want to show a message like id doesn't exist
apply a check if result length is 0 then console message
server.on('request', (req, res) => {
case '/get':
req.on('end', () => {
let id = reqUrl.query.id;
let sql = `Select * from students WHERE id= ${id} `;
con.query(sql, function (err, result) {
if (err) throw err;
if(result.length)
console.log("Found");
else
console.log("id not found");
});
})
res.end('');
});

Categories