2017-06-21 46 views
1

我需要根據服務類型過濾我的業務文檔。如何在填充後的mongodb後過濾

var BusinessSchema = Schema({ 
    name: String, 
    slug: String, 
    service: [{type: Schema.ObjectId, ref: 'Service'}], 
    owner: {type: Schema.ObjectId, ref: 'User'} 

}); 

module.exports = mongoose.model('Business', BusinessSchema); 

和架構服務:

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var ServiceSchema = Schema({ 
    name: String, 
}); 

module.exports = mongoose.model('Service', ServiceSchema); 

這個陣列的企業只需要那些有它的服務「服務A」例如內。

"business": [ 
     { 
      "_id": "594957df4e195d2500324726", 
      "owner": "59482e80d4df7208503154b8", 
      "slug": "Almacene2s", 
      "name": "Almacene2s", 
      "__v": 0, 
      "service": [ 
       { 
        "_id": "594ab160778ae82c44af3a78", 
        "name": "Service C", 
        "__v": 0 
       }, 
       { 
        "_id": "594ab1be778ae82c44af3a7a", 
        "name": "Service D", 
        "__v": 0 
       } 
      ], 

     }, 
     { 
      "_id": "5948483e6bcc1f2788b09145", 
      "owner": "59482e80d4df7208503154b8", 
      "slug": "guaranda-2", 
      "name": "Guaranda Fig", 

      "service": [ 
       { 
        "_id": "594ab160778ae82c44af3a78", 
        "name": "Service A", 
        "__v": 0 
       }, 
       { 
        "_id": "594ab1be778ae82c44af3a7a", 
        "name": "Service B", 
        "__v": 0 
       } 
      ], 

     } 
] 

在這種情況下,結果我想要得到的是:

{ 
      "_id": "5948483e6bcc1f2788b09145", 
      "owner": "59482e80d4df7208503154b8", 
      "slug": "guaranda-2", 
      "name": "Guaranda Fig", 

      "service": [ 
       { 
        "_id": "594ab160778ae82c44af3a78", 
        "name": "Service A", 
        "__v": 0 
       }, 
       { 
        "_id": "594ab1be778ae82c44af3a7a", 
        "name": "Service B", 
        "__v": 0 
       } 
      ], 

     } 

對我來說,能夠進行這種搜索是非常重要的,因爲該系統將允許用戶以選擇篩選具有所需服務的業務。

這是我在nodejs + mongodb上的第一個項目,在繼續之前,我希望得到您的幫助。非常感謝您

回答

0

使用$lookup,這裏是你能達到什麼:

Service.aggregate([ 
    { 
     $match: { 
      "name": "Service A" 
     } 
    }, 
    { 
     $lookup: { 
      from: "business", 
      localField: "_id", 
      foreignField: "service", 
      as: "businesses" 
     } 
    } 
], function(err, result) { 
    console.log(result); 
}); 

在此聚集的管道,你的第一場比賽,並找到名稱爲「服務」服務文檔。然後在service中查找匹配的業務文檔數組,並將它們放在businesses字段中。結果如下所示:

{ 
    "_id" : "594af96883ab76db8ecd021b", 
    "name" : "Service A", 
    "businesses" : [ 
     { 
      "_id" : "594af9a683ab76db8ecd0225", 
      "slug" : "Almacene2s", 
      "owner" : "59482e80d4df7208503154b8", 
      "name" : "Almacene2s", 
      "service" : [ 
       "594af96883ab76db8ecd021b", 
       "594af96883ab76db8ecd021d" 
      ] 
     } 
    ] 
}