【问题标题】:mongoose populate references in same collection猫鼬在同一个集合中填充引用
【发布时间】:2016-12-22 07:42:43
【问题描述】:

我有 ItemCatalog 集合,其中包含类型、单元、项目。

var Categories = new Schema({
  typeName: String
});


var MeasurementUnit = new Schema({
  unit: String
});

var Items = new Schema({
 itemName: String,
 itemStrength: String,
 idType: { type: Schema.Types.ObjectId, ref: 'Categories' },
 idUnit: { type: Schema.Types.ObjectId, ref: 'MeasurementUnit' },
 isActive: Boolean
});


var ItemCatalog = new Schema({
 type: Categories,
 unit: MeasurementUnit,
 items: Items
});

集合文档如下所示

{
"_id": ObjectId("57b188d67aa27ae4ee87e11c"),
"type": [ 
    {
        "_id" : ObjectId("57b188d6e128064381ae2f2f"),
        "typeName" : "abc"
    }
],
"__v": 0,
"unit": [ 
    {
        "_id" : ObjectId("57b188e4e128064381ae2f54"),
        "unit" : "mg"
    }
],
"items": [ 
    {
        "itemStrength" : "100",
        "itemName" : "a1",
        "idType" : ObjectId("57b188d6e128064381ae2f2f"),
        "idUnit" : ObjectId("57b188e4e128064381ae2f54"),
        "isActive" : true,
        "_id" : ObjectId("57b188f3e128064381ae2f7a")
    }
 ]
}

如何检索处于活动状态并填充 idType 和 idUnit 的项目数据,而不是获取整个文档并在客户端循环?

想要这样的数据

{
_id: "57b188d67aa27ae4ee87e11c",
drugs: [
        {
            itemStrength: "100",
            itemName: "a1",
            typeName: "abc",
            unit: "mg",
            isActive: true,
            _id: "57b188f3e128064381ae2f7a"
        }
     ]
 }

请建议最好的实现方式。

【问题讨论】:

  • 我认为不可能使用人口,因为typeunit 存储为sub documents,而不是在单独的集合中。
  • 谢谢@robertklep

标签: node.js mongodb mongoose mongoose-populate


【解决方案1】:

试试这个:

ItemCatalog.find({"items.isActive" : true},{'items.$' : 1}).populate('items.$.idType').populate('items.$.idUnit').exec(function(err,result){...});

items.isActive 需要检查哪个是活动的。

items.$ 仅用于返回 items 数组中处于活动状态的元素。

item.$.idType 只能从匹配的数组元素中填充。

希望这对你有用。

【讨论】:

  • 您的itemsarray of item 还是一个item?同样typeunit 分别是array 或只是一个category a,d measurementUnitarray
猜你喜欢
  • 1970-01-01
  • 2021-08-04
  • 2013-01-13
  • 1970-01-01
  • 2021-06-03
  • 2019-08-29
  • 2015-06-10
  • 2020-11-08
  • 2015-12-23
相关资源
最近更新 更多