2016-11-07 43 views
0

修改子文檔我有一個貓鼬這樣的查詢:只選擇從蒙戈

var query = Events.findOneAndUpdate({ '_id': event._id,'participants._id':participant._id},{'$set': {'participants.$': participant}}, {upsert:false,new: true},function(err,result){ 
    if(err){ 
     return res.status(500).jsonp({ 
      error: 'Unable to update participant' 
     }); 
    } 
    console.log(result.participants[0]); 
    res.jsonp(result.participants[0]); 
}); 

和查詢工作正常修改參與者子文檔內的事件集合。

問題:

我只需要修改的參與者將返回JSON和我不是需要整個參與者陣列的,但我不能做到這一點,因爲我讓所有的參與者時,我做console.log(result.participants);

如何在查詢後只獲取修改後的子文檔?

回答

0

您可能需要使用本機JS filter()方法如下所示:

Events.findOneAndUpdate(
    { '_id': event._id, 'participants._id': participant._id }, 
    { '$set': { 'participants.$': participant } }, 
    { upsert: false, new: true }, 
    function(err, result){ 
     if(err){ 
      return res.status(500).jsonp({ 
       error: 'Unable to update participant' 
      }); 
     } 
     var modified = result.participants.filter(function(p){ 
      return p._id === participant._id 
     })[0]; 
     console.log(modified); 
     res.jsonp(modified); 
    } 
); 
+0

感謝。看起來這是唯一的方法(儘管它沒有效率循環)。 –