簡體   English   中英

貓鼬填充相同集合中的引用

[英]mongoose populate references in same collection

我有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"
        }
     ]
 }

請提出實施相同方法的最佳方法。

嘗試這個:

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

items.isActive到必需的檢查是否處於活動狀態。

items.$僅返回有效的items數組元素。

僅從匹配的數組元素填充item.$.idType是必需的。

希望這對您有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM