如何获取特定的子文档

时间:2019-03-07 20:29:22

标签: node.js mongodb mongoose mongoose-schema subdocument

我有这个特殊的模式

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
            }
        }]
    }]
});
我想找到一个特定的子文档,还想找到一个特定的subCategories.subCategories,我知道如何实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

您可以使用MongoDb的$elemMatch查询运算符(https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#op._S_elemMatch)来完成此操作。

在猫鼬中,您可以这样使用它:https://mongoosejs.com/docs/api.html#query_Query-elemMatch

CategorySchema.find().elemMatch('subCategories', { name: 'CATEGORY_NAME_TO_SEARCH_FOR'});
相关问题