0

I have this particular schema

var CategorySchema=mongoose.Schema({
    name:{
        type:String,
        index:true,
        unique:true
    },
    commission:{
        type:Number
    },
    subCategories:[{
        name:{
            type:String,
            unique:true,
            sparse:true
        },
        subCategories:[{
            name:{
                type:String,
                unique:true,
                sparse:true
            }
        }]
    }]
});
I wanted to find a specific sub document and also wanted to find a specific subCategories.subCategories any idea how i can achive this?
hassanqshi
  • 353
  • 2
  • 9

1 Answers1

0

You would do this with MongoDb's $elemMatch query operator (https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#op._S_elemMatch).

In Mongoose, you use it like this: https://mongoosejs.com/docs/api.html#query_Query-elemMatch

CategorySchema.find().elemMatch('subCategories', { name: 'CATEGORY_NAME_TO_SEARCH_FOR'});
Borduhh
  • 1,975
  • 2
  • 19
  • 33