I have a model ItemModel and another model, ItemInstances. Hopefully those names are self-explanatory. I want to create a virtual in my Mongoose ItemSchema that will return the number of ItemInstances that are associated with that Item and that have a status of "In Stock". So far, I've been able to populate the ItemInstances via a virtual property in the ItemSchema, as so:
ItemSchema.virtual('numberInStock', {
ref: 'ItemInstance',
localField: '_id',
foreignField: 'item',
});
This successfully populates the associated ItemInstances (gives me an array). This is the array that is returned:
[
{
_id: new ObjectId("619be4da2f47a46f785a473a"),
item: new ObjectId("619be4d92f47a46f785a472c"),
status: 'Damaged',
__v: 0
},
{
_id: new ObjectId("619be4da2f47a46f785a473c"),
item: new ObjectId("619be4d92f47a46f785a472c"),
status: 'In Stock',
__v: 0
},
{
_id: new ObjectId("619be4da2f47a46f785a473b"),
item: new ObjectId("619be4d92f47a46f785a472c"),
status: 'In Stock',
__v: 0
}
]
I want the virtual itself to filter the ItemInstances that have a status of "In Stock", and then return the number of those.
I know that I could filter the results in a query, but that's not my intention.
What I have tried:
The above. I also tried creating a getter, but I discovered that getter's cannot be async.