I have a schema:
const item = new mongoose.Schema({
prices: {
type: [
{
addOperation: {
type: [
{
_id,
},
],
},
},
],
},
});
Basically, item has array of prices which are also objects, each price has a field (and other fields similar) called addOperation which is also an array, and each addOperation has an id (like prices and item, generated automatically).
My question is, what is the most efficient way to directly query the specific addOperation that I am interested in?
I have the item id, price id and addOperation id.
My "basic instinct" is to just find the item with its id and then loop on the prices and loop on add operations of each price, until I find what I am searching for.
Something like:
const foundItem = await StockItem.findOne({ _id: itemId }).exec();
foundItem._doc.prices.find(({ _id }) => _id === priceId)
.addOperation.find(({ _id }) => _id === addOperationId);
It would work as there wont ever be that many items to be significant for the performance, but still, I want to do it the "right" way.
What is that "right and optimized" way?
I have tried with:
const addOp = await StockItem.findOne({ _id: id, prices: { _id: priceId }}).exec();
const addOp = await StockItem.findOne({ _id: id, "prices._id": priceId }).exec();
const addOp = await StockItem.findOne({ "prices._id": priceId }).exec();
const addOp= await StockItem.findOne({ _id: id }, { prices: { $elemMatch: { _id: priceId } } }).exec();
Neither worked, to at least give me the price. The first returned null, the rest returned the full StockItem document.