[英]finding embedded document with condition in both documents mongoose
I am developing an program with 2 models, building and floor. 我正在开发一个包含2个模型(建筑物和地板)的程序。 The schema are defined as following. 该模式定义如下。
var BuildingSchema = new Schema({
block:{type:String,trim:true},
project_id:{type:String},
floors:[{type:Schema.Types.ObjectId,ref:'Floor'}]
})
var FloorSchema = new Schema({
name:{type:String,trim:true},
building_id:{type:String,ref:'Building'}
}
What I would like to do is to find the floor result with the conditions of floor.name and building.project_id. 我想做的是找到具有floor.name和building.project_id条件的地板结果。 I have tried this but didn't work 我试过了但是没用
floor.find({name:'fname','building_id.project_id':123}).exec()
How do I get what I want? 我如何得到想要的东西? Thanks. 谢谢。
You'll need to make use of $elemMatch to retrieve just the floor. 您将需要使用$ elemMatch仅检索地板。 The mongoosejs docs talk about it here . mongoosejs文档在这里讨论 。
So you might do something like: 因此,您可以执行以下操作:
building.find({"project_id": 123}).where("floors").elemMatch(function(elem){
elem.match("name", "fname");
});
This should only return the floor element that matches {"name": "fname"}
这仅应返回与{"name": "fname"}
匹配的floor元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.