【问题标题】:finding embedded document with condition in both documents mongoose在两个文档中查找带有条件的嵌入文档 mongoose
【发布时间】:2013-04-18 04:15:29
【问题描述】:

我正在开发一个包含 2 个模型(建筑和地板)的程序。架构定义如下。

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'}
}

我想做的是用 floor.name 和 building.project_id 的条件找到楼层结果。我试过了,但没有用

floor.find({name:'fname','building_id.project_id':123}).exec()

我如何得到我想要的?谢谢。

【问题讨论】:

  • 您的 build_id 是一个字符串,但您正在搜索一个数字。你想要“123”吗?

标签: node.js mongodb mongoose


【解决方案1】:

您需要使用$elemMatch 来检索地板。 mongoosejs 文档讨论了它here

所以你可能会这样做:

building.find({"project_id": 123}).where("floors").elemMatch(function(elem){
  elem.match("name", "fname");
});

这应该只返回匹配{"name": "fname"}的地板元素

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 1970-01-01
    • 2012-08-26
    • 2019-12-30
    • 1970-01-01
    • 2016-04-23
    • 2012-06-08
    • 2021-02-21
    • 2022-10-01
    相关资源
    最近更新 更多