Mongo - Inconsistent query responses

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');


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 =;
	var items = [];
	var totalPrice = 0;
	toyId.forEach((toyElement, ind) => {
		Toy.findOne({ id:toyElement }, (err, toy) => {
			if (err) {
				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 = {
			qty: req.query.qty[ind],
			subtotal: toy.price * req.query.qty[ind]
		totalPrice += toy.price * req.query.qty[ind];
		if (ind == toyId.length - 1) {
			res.json({ items: items, subtotal: totalPrice });

So with an input of:


I expect it to return:


Which it does, but only most of the time.
Occasionally, however, it will return something like this:


And I have no idea why. Can anybody help me get this to behave more consistently?

Well I just found out It’s because you’re not supposed to use .find() in a loop. Could somebody please close/delete this?

We will leave it, because it could be a helpful for someone else using .find in a loop.