通过嵌套文档属性进行mongoose查询

时间:2017-02-20 12:32:58

标签: node.js mongodb mongoose

我的猫鼬模式是这样的。

var ProfileAddressSchema = new Schema({
    streetAddress: { type: String, required: true },
    businessAddress: { type: String, required: false },
    country: {type: Schema.Types.ObjectId, ref: 'Country', required: false },
    city: { type: Schema.Types.ObjectId, ref: 'City', required: false },
    province: { type: String, required: false },
    postalCode: { type: String, required: false },
    isDelete: { type: Boolean, default: false },
    sequence: { type: Number,  default: 0 },
    isDefault: { type: Boolean, default: false }
});

var ProfileInfoSchema = new Schema({

    name: { type: String, required: true },
    firstName: { type: String, required: false },
    addressList:[ProfileAddressSchema],

});

我尝试过如下操作,但不起作用。我希望获得与提供的邮政编码匹配的配置文件。

var criteria = {};
criteria.addressList = {}
criteria.addressList.postalCode = new RegExp(searchPrameters.postalCode, "i"); }
serviceHelper.queryModel(ProfileInfo,criteria, { __v: false },  callback);

1 个答案:

答案 0 :(得分:3)

使用dot notation查询嵌入的文档。您的查询结果应该是

ProfileInfo.find({
    "addressList.postalCode": new RegExp(searchPrameters.postalCode, "i")
}).exec(callback);

因此,您可以使用dot notation构建具有bracket notation密钥的查询对象:

var criteria = {};
criteria["addressList.postalCode"] = new RegExp(searchPrameters.postalCode, "i"); 
serviceHelper.queryModel(ProfileInfo,criteria, { __v: false },  callback);

有关更多示例,请参阅Query an Array of Embedded Documents部分中的手册。