Getting MySQL fields in NodeJS - mysql

I know this is possibly a duplicate but I cannot seem to get it to work.
connection.query('SELECT * FROM software', function(err, rows) {
if (err) {
next(new Error(err));
} else {
data.db = rows[1].language;
data.no = rows.length;
console.log(data.db);
}
});
I am trying to reference a specific field in a row retrieved. I have a row called 'Language' in my table so have researched around and found that I can reference the name of the field. When I do this, it throws back undefined in the console. It returns the same when I reference any other field (i.e. id)

Related

Cannot Get Data From Nested SQL Query

const getCompanyShifts = (req, res) => {
try {
const { company_id } = req.params;
connection.query(
`SELECT * FROM jobs WHERE company_fk=${company_id}`,
(err, rowss) => {
if (!err) {
connection.query(
`SELECT * FROM shift WHERE isBooked=1 AND fk_job = ?`,
[rowss.jobsID],
(err, rows) => {
if (err || rows.length === 0) {
res.status(404).json({
success: false,
message: "Company Shifts Not Found!",
err,
});
} else {
const shifts = [];
rows.forEach((row, i) => {
const shift = {
shiftID: rows[i].shiftID,
shiftStartTime: rows[i].startTime,
shiftEndTime: rows[i].endTime,
shiftDate: rows[i].date,
isBooked: rows[i].isBooked,
fk_job: rows[i].fk_job,
fk_guard: rows[i].fk_guard,
};
shifts.push(shift);
});
res.status(200).json({
success: true,
message: "Successfully Retrieved Company Shifts!",
shifts,
});
}
}
);
} else {
res.status(404).json({
success: false,
message: "Company Jobs Not Found!",
});
}
}
);
} catch (error) {
res.status(500).json({
success: false,
message: error.message,
});
}
};
in the first query of the above code, i am getting all the rows from the jobs table. In the second nested query, i am trying to get all rows from the shift table for each of the jobsID returned from the 1st query. But i don't get any data back. The data exists and it should return data but i don't get any data back. What am i doing wrong here ? Please help!
i assume there is a misunderstanding on how the data gets returned and therefore how the second query would work. According to your statement:
[...] i am getting all the rows from the jobs table. In the second nested
query, i am trying to get all rows from the shift table for each of
the jobsID returned from the 1st query. But i don't get any data back.
You are getting multiple rows back. So the first query works. But getting multiple rows back would result in rowss being an array. Therefore rowss.jobsID which is used as input for the next query isn't a correct use of an array and i expect the value of that expression to be undefined which will then result in the second query not returning anything.
To prove that add console.log(rowss) like so:
[...]
connection.query(
`SELECT * FROM jobs WHERE company_fk=${company_id}`,
(err, rowss) => {
console.log(rowss);
[...]
To solve the issue, i suggest to use sql capabilities and issue a join. By doing so, the Database will join the two tables, then returning only rows that fulfill the where condition. The combined statement should look like:
SELECT * FROM jobs WHERE company_fk=${company_id} LEFT JOIN shift ON shift.fk_job = jobs.jobsID WHERE isBooked=1
Hint: Depending on your DB schemes for ob'sand shift you might need to expand the * and list all table names explicitly, e.g. SELECT jobs.jobsID, jobs.<xyz>, shift.isBooked, shift.fk_job [...] FROM [...]. If you have column with same name in both tables, you might need to resolve the conflict which is caused by the join while combining the columns for returning the results like so: SELECT [...] shift.<xyz> as shift_xyz [...] FROM ...[].
As a plus, you also just need one SQL query instead of two.

Changes in the nodejs code for inserting a batch in mySQL table

Here is the code
const add_friend = async (user_id, users) => {
try {
var data1 = [];
for (const user of users) {
data1 += [user,user_id,"Request Pending"];
}
await mysql.query('INSERT INTO friendship SET ?', [data1])
await mysql.end()
}
catch (err) {
throw err
So users is the list of all other user_id's which is coming as a parameter.
user_id is a single id.
What I am trying is to convert it into one list data1 with three values user_id1, user_id2, and request pending after that I want to update the table in one query only.
But the syntax is not correct. What should be the correct syntax. Please help.

Getting auto-generated (via trigger) field from an insert in sequelize

I have a base controller for generic insert/update operations across the whole API, using only a table dictionary so we can use the same function to insert data into many tables.
The problem is there is a table that uses a correlative number generated via trigger, and when sequelize returns the inserted value, it includes the new ID but the correlative field returns empty, and I need it to show it on the interface.
I've thought of just querying the new field again to the API, or querying it on the same save function again when it includes these certain tables names, but is there a way to tell sequelize to "wait" for this new generated value and then return the data alright? Just like getting the new ID
Or maybe this needs to be fixed on the database? I don't have much experience in that field, but we are using MySQL if that helps.
function Init(models, dictionary) {
this.post = (req, res, next) => {
const { obj } = req.body;
const model = models[dictionary[obj._type]];
//Just stripping fields starting with "_"
const objClear = {};
for (const attr in obj) {
if (attr.charAt(0) !== '_') {
objClear[attr] = obj[attr];
}
}
//Saving
model.create(objClear).then(
(objSaved) => {
const data = {
obj: objSaved.get({ plain: true }),
action: 'inserted',
};
//I guess I could query the new row here again
res.json(data);
},
).catch(next);
};
}
module.exports = {
Init,
};
The response looks like:
{"obj":{"TOTAL":"0","ID":14,...,"TRANSACTION_NO":""},"action":"inserted"}
Where TRANSACTION_NO is the field generated with a trigger.
AFAIK, you have to query the new row unless you use Postgres (in which case you might try the Model.create option called "options.returning")
Two quick tests that did NOT solve the problem:
an afterCreate hook - the model still shows fields created by a trigger as null.
a model having a default value from a DB function - the model shows the function call,
not the result of the function (which does make it to the DB field).
Hope someone else has a solution!

Returned data with node js and mysql

When i connect with mysql ,i get this value { id: 14 }
actually i wanna get only 14
this is my code
app.get('/register',function(req,res){
var data = {
"error":1,
"result":""
};
console.log("ams");
connection.query("SELECT id from register",function(err, rows, fields){
if(rows.length != 0){
data["error"] = 0;
data["result"] = rows;
res.json(data);
console.log(data.result[0]);
}else{
data["result"] = 'No data Found..';
res.json(data);
}
});
});
If you're expecting one row only, you could set
data["result"] = rows[0].id;
However, your response is an array of json objects no matter how many results you get. It's much better to setup the res.json() receiver to work with objects, not plain strings/numbers.
It is not possible to get only values as a mysql query result in node with node-mysql (and I don't think there's any other library that would do that, because it doesn't make sense).

Simple Express program for querying a result

I have a snippet of Express code
Below what i am trying to do is pass the table name to keyName by extracting from the request
But I am facing deaslock
i wanted to know whether i am following proper protocols for JSON response
[Part-of-Express-Code]
app.get('/RestaurantDesc/:Key',function(request,response,next){
var keyName=request.query.Key;
var name_of_restaurants, RestaurantTimings;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM ',keyName, function(err, rows, fields)
{
console.log('Connection result error '+err);
name_of_restaurants = rows;
callback();
});
},
// Get the second table contents
function ( callback ) {
connection.query('SELECT * FROM RestaurantTimings', function(err, rows, fields)
{
console.log('Connection result error '+err);
RestaurantTimings = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'restaurants' : name_of_restaurants,
'RestaurantTimings' : RestaurantTimings
});
} );
} );
I am getting the output as Cannot GET /RestaurantDesc/
Any Ideas
your route should be path, A path that you can access through GET request.
for ex: you should be able to access it through
http://example.com/RestaurantDesc/anyKeyHere
and in your code you have
var keyName = request.query.Key
req.query contains query variables see http://expressjs.com/api.html#req.query
So your keyName variable won't contain anyKeyHere.
req.params.Key will contain value anyKeyHere;
but you will need to pass it in url path.
if you need to pass key data in query you can do this.
app.get('/RestaurantDesc',function(request,response,next){
var keyName=request.query.Key;
});
and pass key like this in your url
http://example.com/RestaurantDesc/?Key=restaurnetkeyHere
Try going through guide in express site and understand routings and how it works.
If you getting "Cannot GET /RestaurantDesc/" is because you have not setup this route, try /RestaurantDesc/something. request.query is used for search terms, ie things that come after a questionmaek in a url. Use request.param.Key instead.
Also for best practices you should lowercase resource names and use the shorter req/res instead of request/response.