2016-12-01 59 views
0

以下是兩種貓鼬模式:如何通過標準找到子文檔+貓鼬/ MongoDB的

EmployeeSchema:

var EmployeeSchema = new Schema({ 
    name : String, 
    employeeDetailsId: { 
     type: Schema.Types.ObjectId, 
     ref: 'employeedetails' 
    } 
}); 

EmployeeDetailSchema:

var EmployeeDetailSchema = new Schema({ 
    employeeId: { 
     type: Schema.Types.ObjectId, 
     ref: 'employee' 
    }, 
    statusId: { 
     type: Schema.Types.ObjectId, 
     ref: 'status' 
    } 
}); 

EmployeeDetailSchema數據獲取按需保存,例如當某個特定狀態分配給員工時。在這種情況下,一旦EmployeeDetail保存文檔則對應EmployeeDetailID保存回EmployeeSchema爲employeeDetailsId

現在有EmployeeSchema和EmployeeDetailSchema之間的雙向關係。

用例:

我想取誰的標籤與特定狀態的所有員工。說輸入狀態ID爲1234然後我想要在EmployeeDetail文檔中獲取狀態ID爲1234的所有員工。

下面是我嘗試使用貓鼬的辦法:即返回空數組雖然有誰被分配到一些狀態的員工

exports.getEmployeesByStatus = function (req, res) { 
    console.log('Status ID : ' + req.query.statusId); 

    EmployeeModel.find({'employeeDetailsId.statusId': {$eq: mongoose.Types.ObjectId(req.params.statusId)}}) 
     .exec(function (err, result) { 
      if (err)res.send('400', {message: 'Unable to fetch employees data by status. Please try again later'}); 

      res.jsonp(result); 
     }); 
}; 

結果。我對Mongoose的查詢方法正確嗎?

+0

您使用的子文檔或使用員工詳細模型的參考價值爲'employeeDetailsId'? –

+0

夫婦約MongoDB的其他很好的問題:通過標準查找子文檔:[一](http://stackoverflow.com/questions/16845191)和【二】(http://stackoverflow.com/questions/21142524)。認爲它可能會幫助其他人。 – BeingSuman

回答

1

您根據您的架構設計中使用的EmployeeDetailSchema參考爲employeeDetailsId。因此您無法直接比較參考模型字段而無需填充。你應該首先填充然後比較和過濾文件,或者用戶可以實現你的目標。

可以試試這個:

EmployeeModel.aggregate([ 
     {$lookup: {from: 'employeedetails', localField: 'employeeDetailsId',foreignField: '_id',as: 'details'}}, 
     {$match: { $and:[{ "details.statusId": { "$exists": true } },{"details.statusId": req.params.statusId}]} } 
    ]).exec(function (err, result) { 
      if (err) return res.send('400', {message: 'Unable to fetch employees data by status. Please try again later'}); 

      return res.jsonp(result); 
     }); 

NB:轉換字符串的ObjectIdreq.params.statusId

{$match: {$and: [{"details.statusId": {"$exists": true}}, {"details.statusId": mongoose.Types.ObjectId(req.params.statusId)}]}} 
+0

感謝回覆的人,我甚至知道'$ lookup'。通過MongoDB文檔瞭解了相同的情況,發現你的答案對我的用例非常有效。但是運行同樣的提取沒有結果,它仍然是空的[]結果。只是想檢查Mongoose是否支持'$ lookup'的'aggregate'?任何參考文件plz。 – BeingSuman

+0

我使用MongoDB中終端作爲簡單的查詢,通過排除在比賽最後檢查,它給了我希望的結果: 'db.getCollection(「僱員」)。骨料([ { $查找: { 來自: 「employeedetails」, localField: 「employeeDetailsId」, foreignField: 「_id」, 爲: 「詳細信息」 } }, { $比賽:{ $和:[{「details.statusId」:{「$ exists」:true}}]} } ]);' – BeingSuman

+0

但前一個查詢的問題是:我已經移除了條件檢查'{「details.statusId 「:req.params.statusId}'。在增加,這再次給了同樣的老問題:'取指0結果' – BeingSuman