2016-08-16 43 views
0

我有ItemCatalog集合,其中包含類型,單位,項目。集看起來像下面貓鼬在同一集合中填充引用

{ 
"_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") 
    } 
] 
} 

我怎麼能檢索的活躍和項目數據的

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 
}); 

文件填充idType和idUnit,而不是獲取整個文檔,並在客戶端循環?

想要的數據是這樣的

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

請建議最好的方式來實現相同的。

+1

我不認爲這是可能的使用人口,因爲'type'和'unit'存儲爲[子文檔](http://mongoosejs.com/docs/subdocs.html),而不是在單獨的集合中。 – robertklep

+0

謝謝@robertklep – vijay

回答

0

試試這個:

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

items.isActive所需檢查這是積極的。

items.$僅用於返回活動的items數組的元素。

item.$.idType只需填充匹配的數組元素。

希望這對你有用。

+0

謝謝,但它不工作。 – vijay

+0

是你的'物品'一個'物品數組'或只是一個'物品'?同樣''type''和'unit'''是'array'還是隻是一個'category' a,d'measurementUnit'或者''''這些數組呢? –