2017-04-05 41 views
0

我以mongodb開頭,我正在使用聚合函數,它給了我sampleStatus數組中最後一個元素的最後一個用戶。 (我指的是最新的記錄添加到sampleStatus)如何使用mongo的聚合返回響應?

我有樣品的這樣一個集合:

{ 
    "_id" : ObjectId("58d6cbc14124691cd8154d72"), 
    "correlativeCode" : "CSLLPA53E20M017W", 
    "registrationMethod" : "taken", 
    "originPlace" : "SOMEPLACE", 
    "temperature" : 16, 
    "sampleStatus" : [ 
     { 
      "nameStatus" : "status1", 
      "place" : "place1", 
      "rejectionReason" : "Nothing", 
      "user" : "user1", 
      "_id" : ObjectId("58d6cbc14124691cd8154d73") 
     }, 
     { 
      "nameStatus" : "status2", 
      "place" : "place2", 
      "rejectionReason" : "Nothing", 
      "user" : "user4", 
      "_id" : ObjectId("58d6cbc14124691cd8154d73") 
     }, 
     { 
      "nameStatus" : "status3", 
      "place" : "place3", 
      "rejectionReason" : "Nothing", 
      "user" : "user3", 
      "_id" : ObjectId("58d6cbc14124691cd8154d73") 
     }, 
     { 
      "nameStatus" : "status4", 
      "place" : "place4", 
      "rejectionReason" : "Nothing", 
      "user" : "user1", 
      "_id" : ObjectId("58d6cbc14124691cd8154d73") 
     }, 
     { 
      "nameStatus" : "status5", 
      "place" : "place5", 
      "rejectionReason" : "Nothing", 
      "user" : "user5", 
      "_id" : ObjectId("58d6cbc14124691cd8154d73") 
     } 
    ] 
} 

這是我使用的功能:

db.collection.aggregate([ 
    { "$match": { "correlativeCode": "CSLLPA53E20M017W" } }, 
    { "$redact": { 
     "$cond": [ 
      { "$eq": [ 
       { "$let": { 
        "vars": { 
         "item": { "$arrayElemAt": [ "$sampleStatus", -1 ] } 
        }, 
        "in": "$$item.user" 
       } }, 
       "user5" 
      ] }, 
      "$$KEEP", 
      "$$PRUNE" 
     ] 
    }} 
]) 

當我使用這個在mongodb的控制檯中,它可以工作..但是,當我嘗試在控制器中適應這種情況時.js

VerifySample: function (req, res) { 
    var id = req.body.idSample; 
    var idUser=req.body.currentuser; 

    SamplePatientModel.aggregate([ 
     { $match: { _id: id } }, 
     { $redact: { 
      $cond: [ 
       { $eq: [ 
        { $let: { 
         vars: { 
          "item": { $arrayElemAt: [ "$sampleStatus", -1 ] } 
         }, 
         in: "$$item.user" 
        } }, 
        idUser 
       ] }, 
       "$$KEEP", 
       "$$PRUNE" 
      ] 
     }} 
    ], 

    function(err, _SamplePatient) { 
      console.log('entry function'); 

      if (err) { 
      console.log('Entry err'); 
       return res.status(500).json({message: 'Error SamplePatient', error: err}); 
      } 
      //No results 
      if(!_SamplePatient){ 
      console.log('no results '); 
      return res.status(404).json({message: 'error', error: err}); 
      } 

      console.log('Got it'); 
      console.log(_SamplePatient); 


      return res.status(200).json(_SamplePatient); 
      } 
    );} 

它給我以下回應:

[] 

console.log(_SamplePatient)不顯示任何

寫着「入口函數」印在控制檯

我究竟做錯了什麼?

請幫幫我。

謝謝。

+0

非常感謝@veeram –

回答