I have two tables which are give in at this fiddle.
http://sqlfiddle.com/#!9/d37102
I want to retrieve data from the table currently I am doing this way
mysqlConnection.query("SELECT* FROM wallet WHERE user_id = ? ORDER by date",authData.id,(err,rows,fields)=>{
if(!err){
res.json({
message :"Statement",
rechargeDetails : rows,
transactionDetail://// TODO: Transaction details
});
}
else console.log(err);
});
That is correctly retrieving the JSON data in at this format over here
{
"message": "Statement",
"rechargeDetails": [
{
"id": 17,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
},
{
"id": 18,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
}
]
}
I want to get transaction table data also like this
{
"message": "Statement",
"rechargeDetails": [
{
"id": 17,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
},
{
"id": 18,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
}
"transactionDetails": [
{
"id": 17,
"amount": 50,
"tax": "CREDIT",
"discount": "xxxxq123",
"adjustment": null,
"refrence_id": "REFUND",
"payment_ref_id": 1,
xxxxxx
xxxxxxxxxx
}
],
}
How could i do that? Is there a way to do this?
mysqlConnection.query("SELECT * FROM wallet WHERE user_id = ? ORDER by date",authData.id,(err,rows,fields)=>{
if(!err){
mysqlConnection.query("SELECT * FROM transaction WHERE user_id = ? ORDER by date",authData.id,(errTarn,rowsTarn,fieldsTarn)=>{
if(!errTarn){
res.json({
message :"Statement",
rechargeDetails : rows,
transactionDetail: rowsTarn
});
}
});
}
else console.log(err);
});
OR YOU CAN USE MULTIPLE QUERY
enable it for your connection
var connection = mysql.createConnection({multipleStatements: true});
Now the code will be
connection.query('SELECT * FROM wallet WHERE user_id = ? ORDER by date; SELECT * FROM transaction WHERE user_id = ? ORDER by date', [authData.id, authData.id], function(err, results) {
if (err) throw err;
if(!err){
res.json({
message :"Statement",
rechargeDetails : results[0],
transactionDetail: results[1]
});
}
});
I have zero knowledge with NODE but I think something like this should work properly
mysqlConnection.query("SELECT* FROM wallet WHERE user_id = ? ORDER by date",authData.id,(err,rows,fields)=>{
if(!err){
res.json({
message :"Statement",
rechargeDetails : rows,
transactionDetail: mysqlConnection.query("__SELECT_TRANSACTIONS_QUERY__",authData.PARAMETER_NEEDED,(err,rows,fields)=>{
if(!err){
// return your rows
}
});
});
} else {
console.log(err);
}
});
Related
I'm building a simple API with express and sqlite. I want my GET request to only display certain keys in each JSON object that is displayed in response.
Below is my current code:
router.get('/cars', (req, res) => {
// TODO GET all cars
try {
let sql = 'SELECT * FROM cars'
let params = []
db.all(sql, params, (err, rows) => {
if (err) {
res.status(400).json({"error":err.message});
return;
}
else {
res.status(200).json({
message: 'success',
data: rows
})
}
});
} catch(error) {
console.log(error.message.red)
res.status(500).json({
message: 'Not found.'
})
}
})
Right now, the response will display entries from the database with all keys and their values. It looks like this:
{
"message": "success",
"data": [
[
{
"car_id": 48,
"email": "honoland13#japanpost.jp",
"name": "Hernando",
"year": 2015,
"make": "Acura",
"model": "TLX",
"racer_turbo": 0,
"racer_supercharged": 0,
"racer_performance": 2,
"racer_horsepower": 2,
"car_overall": 4,
"engine_modifications": 4,
"engine_performance": 0,
"engine_chrome": 2,
"engine_detailing": 4,
"engine_cleanliness": 4,
"body_frame_undercarriage": 2,
"body_frame_suspension": 4,
"body_frame_chrome": 2,
"body_frame_detailing": 2,
"body_frame_cleanliness": 2,
"mods_paint": 2,
"mods_body": 2,
"mods_wrap": 0,
"mods_rims": 4,
"mods_interior": 4,
"mods_other": 4,
"mods_ice": 6,
"mods_aftermarket": 2,
"mods_wip": 0,
"mods_overall": "4",
"score": 62
},
...
I just want to display the car_id, email, name, year, make, model, and score keys and their values and omit the rest of the keys.
I've tried using a forEach loop like so
if(err) {
res.status(400).json({'error':err.message});
return;
} else {
res.json({
message:'success',
data: rows.forEach((row) => {
row.car_id,
row.email,
row.name,
row.year,
row.make,
row.model,
row.score
}
})
}
But it doesn't show the data, but I'm not getting any errors in my console either.
Expected output is this:
"message": "success",
"data": [
[
{
"car_id": 48,
"email": "honoland13#japanpost.jp",
"name": "Hernando",
"year": 2015,
"make": "Acura",
"model": "TLX",
"score": 62
},
...
Any help is really appreciated.
try this
let sql = 'SELECT car_id,email,name,year,make,model,score FROM cars'
I am getting 'TypeError: Cannot convert undefined or null to object' while trying to access the length of json object in nodejs.
Following is how my data looks like:
{
"college": [
{
"colleges": [],
"department": [
1,
2,
3
],
"general_course": [],
"id": 1,
"name": "College of the Arts",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1919"
},
{
"colleges": [],
"department": [
4,
5,
6
],
"general_course": [],
"id": 2,
"name": "College of Communications",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1920"
},
{
"colleges": [],
"department": [
7,
12
],
"general_course": [],
"id": 3,
"name": "College of Education",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1921"
},
{
"colleges": [],
"department": [
13,
17,
19
],
"general_course": [],
"id": 4,
"name": "College of Engineering and Computer Science",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1922"
},
{
"colleges": [],
"department": [
20,
26,
27
],
"general_course": [],
"id": 5,
"name": "College of Health and Human Development",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1923"
},
{
"colleges": [],
"department": [
28,
29,
32,
48
],
"general_course": [],
"id": 6,
"name": "College of Humanities and Social Sciences",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1924"
},
{
"colleges": [],
"department": [
52,
57
],
"general_course": [],
"id": 7,
"name": "College of Natural Sciences and Mathematics",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1925"
},
{
"colleges": [],
"department": [
58,
59,
63
],
"general_course": [],
"id": 8,
"name": "Mihaylo College of Business and Economics",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1926"
}
]
}
Step 1 - Parsing it into nodejs:
let colleges = JSON.parse(data)
Step 2 - Saving it into the dialogflow app data:
app.data.collegeData = data;
Step 3 - Accessing the length:
let collegeLength = Object.keys(app.data.collegeData.college).length;
Getting following error in firebase console:
TypeError: Cannot convert undefined or null to object
Update:
Here is the code:
if ( app.data.collegeData === undefined ){
app.data.collegeData = [];
}
**Step 1 =>**
showColleges(college);
**Step 2 =>**
function showColleges(collegeName){
if (app.data.collegeData.length === 0){
getCollegeData().then(buildSingleCollegeResponse(collegeName))
.catch(function (err){
console.log('No college data')
console.log(err)
});
}
else{
buildSingleCollegeResponse(collegeName);
}
}
**Step 3 =>**
function getCollegeData(){
console.log('Inside get College Data')
return requestAPI(URL)
.then(function (data) {
let colleges = JSON.parse(data)
if (colleges.hasOwnProperty('college')){
saveData(colleges)
}
return null;
})
.catch(function (err) {
console.log('No college data')
console.log(err)
});
}
**Step 4 =>**
function saveData(data){
app.data.collegeData = data;
console.log(app.data.collegeData)
}
**Step 5 =>**
function buildSingleCollegeResponse(collegeName){
let responseToUser, text;
//console.log('Data is -> '+ Object.keys(app.data.collegeData.college).length);
//console.log('Length is -> '+ app.data.collegeData.college.length);
console.log('Count is -> '+app.data.collegeCount);
let collegeLength = Object.keys(app.data.collegeData.college).length;
if ( collegeLength === 0){
responseToUser = 'No colleges available at this time';
text = 'No colleges available at this time';
}
else if ( app.data.collegeCount < collegeLength ){
for ( var i = 1; i <= collegeLength; i++)
{
console.log('All Colleges:: '+app.data.collegeData.college[i])
let coll = app.data.collegeData.college[i]
let name = coll.name
console.log('checkCollegeExist => College Name:: '+ name)
console.log('checkCollegeExist => Parameter => College Name:: '+collegeName)
if(String(name).valueOf() === String(collegeName).valueOf()){
responseToUser = 'Yes! CSUF has '+collegeName;
text = 'Yes! CSUF has '+collegeName;
}else{
responseToUser = 'CSUF does not teach ' +collegeName+' currently';
text = 'CSUF does not teach ' +collegeName+' currently';
}
}
}
else{
responseToUser = 'No more colleges';
}
if (requestSource === googleAssistantRequest) {
sendGoogleResponse(responseToUser);
} else {
sendResponse(text);
}
}
This is the culprit:
getCollegeData().then(buildSingleCollegeResponse(collegeName))
That calls buildSingleCollegeResponse(collegeName) and then passes its return value into then, just like foo(bar()) calls bar and passes its return value into foo.
You wanted to pass a functon to then:
getCollegeData().then(() => buildSingleCollegeResponse(collegeName))
// An arrow function ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note that now that it's clear from the updated question that app.data.collegeData.college is an array, there's no need for Object.keys. Change:
let collegeLength = Object.keys(app.data.collegeData.college).length;
to simply
let collegeLength = app.data.collegeData.college.length;
Arrays have a length property (whereas non-array objects don't, by default).
You haven't mentioned what value app.data holds before issuing app.data.collegeData = data;
If app.data is undefined you should try app.data = {collegeData: data}
Or else negating what app stores. Following works
app = {};
app.data = {};
app.data.collegeData = data;
app.data.collegeData.college.length
You don't need to do the following
let collegeLength = Object.keys(app.data.collegeData.college).length;
Update: Refer to https://jsfiddle.net/dmxuum79/3/
I am very confused to use Bookshelf model to insert data to database in this situation:
I am using these libs:
knex, bookshelf, express, body-parser, and mysql database
I have a table on db is called location, it contains below column:
loc_id, latitude, longitude, time
This location is sending from one user, so I need to save loc_id in another table with user_id
to save a location (single object) without saving user_id I use this code:
.post(function (req, res) {
Loc.forge({latitude: req.body.location.lat,
longitude: req.body.location.lng,
date:req.body.time,
speed:req.body.speed,
gpsAnten:req.body.gpsAnten})
.save()
.then(function (location) {
res.json({error: false, data: {id: location.get('id')}});
})
.catch(function (err) {
res.status(500).json({error: true, data: {message: err.message}});
});
});
but now, I am sending post request by body like below from my device:(it is JSON format)
{
"user_id": 135,
"locations": [
{
"id": 1,
"latitude": "35.374760",
"longitude": "51.5123916",
"date": "0000-00-00 00:00:00"
},
{
"id": 2,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 3,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 4,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 5,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 6,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
}
]
}
How could I save each location in location table and get this Id, then save its loc_id and user_id in loc_user table ?
At least I found the solution to fix this issue; here is my code:
.post(function (req, res) {
deviceId = req.body.id
locationArray = req.body.frame;
locationArray.forEach(function(element) {
console.log(element);
Loc.forge({latitude: element.location.lat,
longitude: element.location.lng,
date: element.time,
speed: element.speed,
gpsAnten: element.gpsAnten})
.save()
.then(function (location) {
userDevice.forge({
device_id: deviceId,
location_id: location.get('id')
})
.save()
.then(function(middleware) {
console.log('Save middleware');
})
.catch(function(err) {
console.log('Error middleware:' + err.message);
})
})
.catch(function (err) {
console.log('Error location:' + err.message);
});
});
});
It is not as clear as I need but seems is only solution.
I am trying to figure out how to output a structured JSON from a query to my API. I have the following 2 tables (MySQL):
**TABLE1:**
uid
name
pptw
**TABLE2**
id
table1_uid
assignment
start_time
end_time
date
comments
And this is the JSON output I am looking for:
$scope.table1 = {
"toplevel":
[
{
"uid": 1,
"name": "john",
"pptw": "ATWF",
"child":
{
"id": 1,
"table1_uid": 1,
"assignment": null,
"start_time": "14:53:00",
"end_time": "15:00:00",
"date": null,
"comments": null
}
},
{
"uid": 22,
"name": "carol",
"pptw": "DWFF",
"child":
{
"id": 2,
"table1_uid": 22,
"assignment": null,
"start_time": "11:00:00",
"end_time": "14:00:00",
"date": null,
"comments": "Completed"
}
}
]
}
I have a promise as follow:
var request = $http({
method: 'post',
url: '.../api/v1/ppp',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
//record_uid: record_uid,
}
})
.success(function (data, status, headers, config) {
deferred.resolve(data);
})
.error(function (data, status) {
deferred.reject();
});
return deferred.promise;
And on the database, I have the following query:
SELECT tb1.uid
tb1.name
tb1.pptw,
tb2.id,
tb2.table1_uid,
tb2.assignment,
tb2.start_time,
tb2.end_time,
tb2.date,
tb2.comments
FROM
table1 tb1, table2 tb2
WHERE
tb1.uid = tb2.table1_uid
I would appreciate any ideas on how to achieve this, thanks a lot.
This is the solution to my questions, I managed to figure out how to do it. I hope it helps someone else trying to do the same thing as I did.
Here is how to create the hierarchical JSON:
var results_tree_header = [];
var results_tree = [];
if (result.rows.length > 0) {
for (var i = 0; i < result.rows.length; i++) {
results_tree.push({
"uid": result.rows.item(i).uid,
"name": result.rows.item(i).name,
"pptw": result.rows.item(i).pptw,
"child":
{
"id": result.rows.item(i).id,
"table1_uid": result.rows.item(i).table1_uid,
"assignment": result.rows.item(i).assignment,
"start_time": result.rows.item(i).start_time,
"end_time": result.rows.item(i).end_time,
"date": result.rows.item(i).date,
"comments": result.rows.item(i).comments
}
});
results_tree_header = { toplevel: results_tree };
}
}
I am looking to fetch data from on query and then run a array loop over a item stored in result. then Fetch data from another query using keys from the array fetched from first query.
What ever I have tried is not giving me the desired result as array loops runs out before the sql queried finishes and produce the desired result.
I have tried solution with async.series function and async.map function but result is not coming in the desired sequence.
This is the output From first query.
My objective is to add array of option details in place option id which is returned from first query.
[
{
"id": 318,
"name": "Sandwich Dosa",
"price": 140,
"option": ''
},
{
"id": 319,
"name": "Spi. Prem Uttappa",
"price": 131,
"option": '1,2'
},
{
"id": 320,
"name": "Paneer Spl. Prem Uttappa",
"price": 140,
"option": ''
},
{
"id": 321,
"name": "Spl. Spicy Uttappa",
"price": 131,
"option": ''
}
]
Looking to build as
[
{
"id": 318,
"name": "Sandwich Dosa",
"price": 140,
"option": ''
},
{
"id": 319,
"name": "Spi. Prem Uttappa",
"price": 131,
"option": [{
id:'1',
name:'Regular',
price:'89',
},
{
id:'2',
name:'Spicy',
price:'119',
}]
},
{
"id": 320,
"name": "Paneer Spl. Prem Uttappa",
"price": 140,
"option": ''
},
{
"id": 321,
"name": "Spl. Spicy Uttappa",
"price": 131,
"option": ''
}
]
This is my current code through which I am trying to achive
var data = {
"error": 1,
"items": ""
};
connection.query("SELECT * FROM items WHERE status=1 AND menu_grp_id=" + req.params.sid, function(err, rows, fields) {
var items = []; // temporary holder for items
if(err) { throw err } else {
if(rows.length != 0) {
for (var key in rows) {
// Holding Item properties
var item = {
id: '',
name: '',
price: '',
option: ''
};
item.id = rows[key].id;
item.name = rows[key].item_name;
item.price = rows[key].price;
item.option = rows[key].option;
items.push(item); // pushing item object into items array
}
data["error"] = 0;
data['items'] = items;
if((data['items'].length > 0)) {
for(i = 0; i < data['items'].length; i++) {
if(data['items'][i].option == "") {
data['items'][i].option = [];
} else {
var array = data['items'][i].option.split(",")
data['items'][i].option = array;
}
}
}
res.json(data); // sending JSON Data
} else {
data["error"] = 0;
data["items"] = 'No item Found..';
res.json(data); // sending JSON Data
}}
});
Probably I'm a bit late here, but I think that async.waterfall is what you need.
async.waterfall([
function(cb){
connection.query("SELECT * FROM items WHERE status=1 AND menu_grp_id=" + req.params.sid, function(err, rows, fields) {
//manipulate your data as you wish
data = synchronousManipolutionOfYourData();
cb(null, data);
});
},
function(data, cb){
//data here stores the data you passed as a second parameter in the preciding callback
//execute your second query with the data you got from the first query.
cb(null, dataManipulatedAfterSecondQuery)//and so on
},
//other functions if you need other queries
], function(){
done;
});