2016-08-16 42 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'或者''''这些数组呢? –