I’m trying to make an api that would respond with a JSON object, but I’m only getting the correct results about 4 out of 5 times.
I’m using express and Mongo with Mongoose.
This is the schema:
//This is Toy.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myDatabase');
var Schema = mongoose.Schema;
var toySchema = new Schema( {
id: {type: String, required: true, unique: true},
name: {type: String, required: true},
price: Number
} );
module.exports = mongoose.model('Toy', toySchema);
And this is the relevant part of the express code:
var express = require('express');
var app = express();
var Toy = require('./Toy.js');
app.use('/calculatePrice', (req, res) => {
var toyId = req.query.id;
var items = [];
var totalPrice = 0;
toyId.forEach((toyElement, ind) => {
Toy.findOne({ id:toyElement }, (err, toy) => {
if (err) {
res.type('html').status(500);
res.send('Error: ' + err);
}
else if (req.query.qty[ind] > 0) {
if (toy) {
generateTotal(toy, ind);
}
else if (ind == toyId.length - 1) {
res.json({ items: items, subtotal: totalPrice });
}
}
});
});
function generateTotal(toy, ind) {
var itemObject = {
item: toy.id,
qty: req.query.qty[ind],
subtotal: toy.price * req.query.qty[ind]
};
items.push(itemObject);
totalPrice += toy.price * req.query.qty[ind];
if (ind == toyId.length - 1) {
res.json({ items: items, subtotal: totalPrice });
}
}
});
So with an input of:
/calculatePrice?id[0]=123&qty[0]=2&id[1]=456&qty[1]=3
I expect it to return:
{"items":[{"item":"123","qty":"2","subtotal":21.98},{"item":"456","qty":"3","subtotal":77.97}],"subtotal":99.95}
Which it does, but only most of the time.
Occasionally, however, it will return something like this:
{"items":[{"item":"456","qty":"3","subtotal":77.97}],"subtotal":77.97}
And I have no idea why. Can anybody help me get this to behave more consistently?