I am using sub-documents in my MEAN project, to handle orders and items per order.
These are my (simplified) schemas:
var itemPerOrderSchema = new mongoose.Schema({
itemId: String,
count: Number
});
var OrderSchema = new mongoose.Schema({
customerId: String,
date: String,
items: [ itemPerOrderSchema ]
});
To insert items in itemPerOrderSchema array I currently do:
var orderId = '123';
var item = { itemId: 'xyz', itemsCount: 7 };
Order.findOne({ id: orderId }, function(err, order) {
order.items.push(item);
order.save();
});
The problem is that I obviously want one item per itemId
, and this way I obtain many sub-documents per item...
One solution could be to loop through all order.items
, but this is not optimal, of course (order.items
could me many...).
The same problem could arise when querying order.items
...
The question is: how do I insert items in itemPerOrderSchema
array without having to loop through all items already inserted on the order?