How can I get just the Count result? - json

I have this node msnodesqlv8 connection and I am counting the number of records from one table. I am getting the result as { total: 26 } and the expected result should be 26. Here is my code:
pool.connect().then(() => {
pool.request().query('SELECT count([TaskID]) as total FROM [db_test].[dbo].[tb_test]', (err, result) => {
myResults = result.recordset[0];
console.log(myResults);
})
});

As you are getting data in object form. now you have to access the object from the result.
pool.connect().then(() => {
pool.request().query('SELECT count([TaskID]) as total FROM [db_test].[dbo].[tb_test]', (err, result) => {
myResults = result.recordset[0].total;
console.log(myResults.total); // it should provides you expected result
})
});

Related

NodeJS get the mysql query result

I have a table containing an ISBN number and a the available number of books. I want to make a query to to ISBN number and get the response about the number of the books with this ID, but I don't know how to write the proper function to get the query result?
db.checkPeldanyszam( rentISBN, response, callback) => {
if (err) {
res.status(500).render('error', { message: `Insertion unsuccessful: ${err.message}` });
} else {
console.log(err);
next();
}
});
exports.checkPeldanyszam = (req,callback) => {
console.log(req);
const query = `SELECT Peldanyszam, IF(Peldanyszam>0, "Jo", "Hibas") as isOkay FROM konyv
WHERE ISBN=${req};`
pool.query(query,callback);
}
Thank you.

nodejs mysql query that relies on another query result and afterwards insert in loop the second query result to the first

i need to run a first query that i get from it a list of auctions, i need to run a second query that for each auction i get the lowest bid for this auction.
after i get the results i need to push the lowest bid to the auctions json that i recive from the first query (results1) in for loop.
when i console log results i get a array with 9 object (it should be 3) and the lowest bid property is only exists on 3 of them objects, it might be better way of doing this.
the console.log of results after adding it the lowest bids :
https://imgur.com/a/eiYcycZ
router.get('/get-live-auctions', auth, (req, res) => {
try {
const userID = req.userData.userID;
db.query(`SELECT auctions.UID,auctions.OriginCompany,auctions.DestinationCompany,auctions.OriginAddress,auctions.DestinationAddress,auctions.PickupDate,auctions.TotalWeight,auctions.StartDate,auctions.BidEndDate,auctions.AuctionEndDate,auctions.AuctionState,auctions.AuctionSerialNumber
From auctions
WHERE UserId='${userID}' AND AuctionState = 2 OR AuctionState = 3 OR AuctionState = 4`, (
err, results, fields) => {
for (let i = 0; i < results.length; i++) {
let auctionsIDS = results[i].UID;
db.query(`SELECT MIN(TotalPrice) AS lowestBid
FROM bids
Where AuctionID = '${auctionsIDS}'
`, (err2, results2, fields2) => {
let lowestBid = results2[0].lowestBid;
results.lowestBid = lowestBid;
console.log(results);
if (err2) return res.send(error);
}
)
}
res.status(200).json(results);
});
} catch (error) {
return res.status(500).send("Server error");
}
})
how to solve this issue?

How to insert records in the database and then update some fields?

I want to do a multiplication of items that are separated into groups in my database a certain number of times but when doing the multiplication I need to change the value of a field called GroupNumber.
For this, I am making two HTTP requests within a looping (FOR).
The first one does the copy of what I need and the second one does an UPDATE in the GroupNumber field.
image 1
As you can see the copy is done 3 times, but the value of GroupNumber (Group #) assumes the value of the group of products copied +1 (in case '2') and remains so. I would like the copy to be shown below.
Image 2
Follow the code for review:
products.component.ts
copyProductsOfGroup() {
const quoteID = + this.activatedRoute.snapshot.paramMap.get('id');
const groupNumber = this.copyGroupProductsForm.get('copyGroup').value
const multiplier = this.copyGroupProductsForm.get('multiplier').value
for (let i = 0; i < multiplier; i++) {
this.productService.copyGroupProduct(quoteID, groupNumber)
.subscribe(
(cloneProductsInfos) => {
this.cloneProductsInfos = cloneProductsInfos
console.log(this.cloneProductsInfos)
},
(err) => {
console.log(err)
},
() => {
this.productService.updateCopyGroupProduct(this.groupNumber, this.cloneProductsInfos.insertId, this.cloneProductsInfos.affectedRows)
.subscribe(
(data) => {
console.log(data)
},
(err) => {
console.log(err)
},
() => {
this.getQuotesProducts()
this.filterGroupNumber()
this.modalService.dismissAll()
}
)
}
)
}
}
Service:
product.service.ts
copyGroupProduct(quoteID: number, groupNumber: number): Observable<CloneProductsModel> {
const url = `http://localhost:9095/copy-group/${quoteID}/${groupNumber}`
return this.http.get<CloneProductsModel>(url)
}
updateCopyGroupProduct(newGroupNumber: number, insertID: number, affectedRows: number): Observable<CloneProductsModel> {
const url = `http://localhost:9095/copy-group-update/${newGroupNumber}/${insertID}/${affectedRows}`
return this.http.get<CloneProductsModel>(url)
}
Nodejs and MySQL:
// Copy productGroup
app.get('/copy-group/:quoteID/:groupNumber', function (req, res) {
let quote_id = req.params.quoteID;
let groupNumber = req.params.groupNumber;
mydb.query(`
INSERT INTO products (
ProductName,
ProductElement,
ProductAttribute,
ProductAttributeValue,
Quantity,
ProductNotes,
FK_ID_QUOTE,
ID_POF,
ID_POE
)
(
SELECT
ProductName,
ProductElement,
ProductAttribute,
ProductAttributeValue,
Quantity,
ProductNotes,
FK_ID_QUOTE,
ID_POF,
ID_POE
FROM products AS P
WHERE P.FK_ID_QUOTE = ${quote_id} AND P.GroupNumber = ${groupNumber}
)`,
function (error, results, fields) {
if (error) throw error;
console.log(results)
return res.send(results);
});
});
app.get('/copy-group-update/:newGroupNumber/:insertID/:affectedRows', function (req, res) {
let newGroupNumber = req.params.newGroupNumber;
let insertID = req.params.insertID;
let affectedRows = req.params.affectedRows;
console.log(newGroupNumber)
console.log(insertID)
console.log(affectedRows)
mydb.query(`
UPDATE products AS P
SET P.GroupNumber = ${newGroupNumber}
WHERE P.ID BETWEEN ${insertID} AND (${insertID} + ${affectedRows} - 1)
`,
function (error, results, fields) {
if (error) throw error;
console.log(results)
return res.send(results);
})
})

Fill array of objects with data from multiple mysql querys

Is there a way to pause iteration of map function so I can get response from my query and store it in some object.
So my data is an array of objects and I want to add property "receivers" for every single object in array so I use map funtion to loop through my array, problem is in callback :D ,my object reveive data after my express sends response so I had to dely response with Timeout, I know its not the right solution but it work for now because I have only 40-50 records in database.
Here is the code:
data.map((x) => {
let sql = `
SELECT username
FROM message
JOIN message2user ON message.message_id = message2user.message_id
JOIN user on message2user.receiver_id = user.user_id
where message.message_id = ?;
`;
testDB.query(sql, x.message_id, (err, dataReceivers) => {
if (err) console.log(err);
x["receivers"] = dataReceivers;
})
});
setTimeout(() => {
res.json({ success: true, data: data });
}, 1000);
I am using express for my API routes and MySQL module for node, maybe I sould use Promises or async functions from node, I dont know.
Do you have any ideas??
Here's an approach using Promises if you don't want to refactor your SQL query:
const sqlTemplateString = `
SELECT username
FROM message
JOIN message2user ON message.message_id = message2user.message_id
JOIN user on message2user.receiver_id = user.user_id
where message.message_id = ?;
`;
Promise.all(data.map((x) => new Promise((resolve, reject) => {
testDB.query(sqlTemplateString, x.message_id, (err, dataReceivers) => {
if (err) {
reject(err);
} else {
x.receivers = dataReceivers;
resolve(x);
}
});
}))).then((data) => {
res.json({
success: true,
data
});
}).catch((error) => {
console.log(error);
res.json({
success: false,
error
});
});
Or something like that.

Why is my Mongoose query within a loop only returning the first result?

I have been struggling with this for days now. I am trying to return the data that is referenced by a list of IDs.
Example JSON of one team:
{
"Name":"Team 3",
"CaptainID":"57611e3431c360f822000003",
"CaptainName":"Name",
"DateCreated":"2016-06-20T10:14:36.873Z",
"Members":[
"57611e3431c360f822000003", //Same as CaptainID
"57611e3431c360f822000004" //Other members
]
}
Here is the route:
router.route('/teams/:user_id')
.get(function (req, res) {
TeamProfile.find({
Members : {
$in : [req.params.user_id]
}
}).exec(function (err, teamProfiles) {
teamProfiles.forEach(function (teamProfile) {
UserProfile.find({
UserID : {
$in : teamProfile.Members.map(function (id) {
return id;
})
}
}, function (err, userProfiles) {
teamProfile.Members = userProfiles;
console.log(teamProfile); //will console log the remaining 2
})
.exec(function (err) {
res.json(teamProfile) //returns the first one only
})
})
});
})
The idea is for the route to return the profiles just by using the IDs to fetch the up-to-date data.
However, it is working to a point. It gets the user information and all but it doesn't return all the Teams + all the users as commented in the code. There are 3 teams in total. Only the first one is returned. If I remove res.json(teamProfile) it console logs all 3 teams. I want to return all 3 teams.
This is because your response is being called before completing all db operations. So instead of for each use async.forEach function. Install async module
var async = require('async');
router.route('/teams/:user_id').get(function (req, res) {
TeamProfile.find({
Members : {
$in : [req.params.user_id]
}
}).exec(function (err, teamProfiles) {
async.forEach(teamProfiles,function (teamProfile,cb) {
UserProfile.find({
UserID : {
$in : teamProfile.Members.map(function (id) {
return id;
})
}
}, function (err, userProfiles) {
teamProfile.Members = userProfiles;
cb() // Callback
})
},function(){
res.json(teamProfiles)
})
});
})