2016-08-16 5 views
0

私はタイプが含まれている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

+1

私はそれが人口を使用して可能だとは思わない、なぜなら 'type'が'とunit'は分別回収していない[サブ文書](http://mongoosejs.com/docs/subdocs.html)として保存されています。 – robertklep

+0

ありがとう@robertklep – vijay

答えて

0

はこれを試してみてください。

items.$は、アクティブなアイテム配列の要素のみを返すように提供されています。

item.$.idTypeは、一致する配列要素からのみ入力する必要があります。

これはうまくいきます。

+0

ありがとうございますが、動作していません。 – vijay

+0

あなたの 'items'は' itemの配列 'か単なる' item'ですか?同様に、 'type'と' unit'はそれぞれ 'array'か' a'd' measurementUnit'または 'array'ですか? –

関連する問題