Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

JavaScript
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:

JavaScript
[
  {
    _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.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900