0

How to get the subcategory object with find function in monoose?

This is how Category model look like:

const Category = mongoose.model(
    'Category',
    new mongoose.Schema({
      name: { type: String },
      subCategories: [
        {
          name: { type: String }
        }
      ]
    })
  );

I need to find only one of subCategories with id of 5ccdc3dd4e88235af8923c74.

So I did the query:

Category.find({ "subCategories._id": { '$in': [  mongoose.Types.ObjectId("5ccdc3dd4e88235af8923c74") ] } })

The results comes with the right Category But also with all subCategories that belong to this category and I need only matched subcategory.

How I improve this query to get me the right subCategory and the category nested inside? I only want to use find method for this (no lookup, no arrgigate).

Jon Sud
  • 10,211
  • 17
  • 76
  • 174
  • it's a different question because here I getting the results (I change the function) but not the way I want.. – Jon Sud May 05 '19 at 09:31
  • 1
    Yes spotted you are asking something different now and switched the duplicate. Still missing that the `$in` is not required. The query is correct with or without it, but "filtering arrays" is different to "matching documents". The linked answer explains "filtering arrays" with `$filter`. – Neil Lunn May 05 '19 at 09:32

0 Answers0