2016-12-16 46 views
0

我有三個型號:產品,類別和事件,如何找到在多個子目標對象

這些都是我的模型

product.js

var ProductSchema = new mongoose.Schema({ 

     p_id: Number, 
     p_name: String, 
     p_fk_category: {type: mongoose.Schema.Types.ObjectId, ref: 'categories'}, 

    } 
    , {collection: 'products'}); 


module.exports = mongoose.model('products', ProductSchema); 

Category.js

var CategorySchema = new mongoose.Schema({ 

      c_id: Number, 
      c_name: String, 
      c_fk_event: {type: mongoose.Schema.Types.ObjectId, ref: 'events'}, 

     } 
     , {collection: 'categories'}); 


    module.exports = mongoose.model('categories', CategorySchema); 

Event.js

變種EventSchema =新mongoose.Schema({

 e_id: Number, 
     e_name: String, 
     e_fk_club_id: Number, 

    } 
    , {collection: 'events'}); 


module.exports = mongoose.model('events', EventSchema); 

假設我有:3個產品,2類和2個事件

產品1和產品3屬於類別1

產品2屬於類別2

類別1所屬的事件1

類別2所屬的事件2

事件1具有club_id 1111

事件2有club_id 2222

這是一個例子 產品

{ 
"p_id": 001, 
"p_name": "Product 1", 
"p_fk_category": ObjectId("584fcfa4c50c7ab8ac31ba9f") 
} 

    { 
"p_id": 002, 
"p_name": "Product 2", 
"p_fk_category": ObjectId("584fcfa4c50c7ab8ac31baa0") 
} 

    { 
"p_id": 003, 
"p_name": "Product 3", 
"p_fk_category": ObjectId("584fcfa4c50c7ab8ac31ba9f") 
} 

分類

{ 
"c_id": ObjectId("584fcfa4c50c7ab8ac31ba9f"), 
"c_name": "Category 1", 
"c_fk_event": ObjectId("584592bcf9fec37548e19485") 
} 

{ 
"c_id": ObjectId("584fcfa4c50c7ab8ac31baa0"), 
"c_name": "Category 2", 
"c_fk_event": ObjectId("584592bcf9fec37548e19486") 
} 

活動

{ 
"e_id": ObjectId("584592bcf9fec37548e19485"), 
"e_name": "event 1", 
"e_fk_club_id": 1111 
} 

    { 
"e_id": ObjectId("584592bcf9fec37548e19486"), 
"e_name": "event 2", 
"e_fk_club_id": 2222 
} 

的問題是:在貓鼬,如何獲得產品從e_fk_club_id等於1111,在其他的方式如何,得到產物1和產品3,有類別屬於事件1,其club_id等於1111.

我嘗試了一個深填充的例子,但它並沒有工作。

在此先感謝

回答

1

我得到你的問題,你可以使用$查找聚集查詢。我已經爲你寫了一個查詢檢查它:

db.events.aggregate([{"$match":{"e_fk_club_id":1111}},{"$lookup":{"from":"categories","localField":"e_id","foreignField":"c_fk_event","as":"categories"}},{"$unwind":"$categories"},{"$lookup":{"from":"products","localField":"categories.c_id","foreignField":"p_fk_category","as":"products"}}]).pretty() 
相關問題