I am working on a shopping cart application. The user will add items to their \'cart\' which is being stored in local storage. When the user navigates to a different page from w
This server code is wrong:
viewCartPost: function(req, res){
var data = JSON.parse(req.body.data);
console.log(data);
var keys = Object.keys(data);
//console.log(keys);
for(var i = 0; i<keys.length; i++){
var productId = keys[i];
Product.find({productId: productId}).select({productId : 1, addProductGroupName: 1, productName: 1, productPrice: 1, productDescription: 1, filePath: 1}).exec(function(err, cartProducts){
if(err){
console.log(err);
res.send("error");
}else{
res.send("Success^^^"+cartProducts);
}
});
console.log(productId);
}
},
You have res.send("Success^^^"+cartProducts);
inside a for
loop. That means you're calling it multiple times. That means you're trying to send more than one response for this request and that triggers the error you see. This is faulty server code. You need to only send ONE response for any given request.
I would have to understand what the desired single response is before I could suggest what code would best solve this issue. If you intend to execute multiple asynchronous operations such as this and you want to know when all of them are done, then you have to write code to keep track of them and be notified when they are all done and then send one and only one response.
This can be done manually with a counter and some code to increment and check the counter or it can be done in a more manage way by switching to use promises to keep track of your asynchronous operations and using Promise.all()
to notify you when all the asynchronous operations are done.
When you have multiple keys in this function, what is the desired single response to send?
I don't know mongoose too well myself, but .exec()
in a fairly recent version of mongoose returns a promise so we can use that to coordinate multiple async database operations like this:
viewCartPost: function(req, res){
var data = JSON.parse(req.body.data);
console.log(data);
var keys = Object.keys(data);
//console.log(keys);
var promises = [];
for(var i = 0; i<keys.length; i++){
var productId = keys[i];
promises.push(Product.find({productId: productId}).select({productId : 1, addProductGroupName: 1, productName: 1, productPrice: 1, productDescription: 1, filePath: 1}).exec());
}
Promise.all(promises).then(function(results) {
// you may have to reorganize results to be exactly what you want
// to return to the client
res.json(results);
}).catch(function(err){
console.error("viewCartPost", err);
res.sendStatus(500);
});
},