2016-11-07 20 views
0

ich eine Mungo Abfrage wie dieses:Auswählen nur Subdokument von Mongo modifizierten

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]); 
}); 

und die Abfrage funktioniert Modifizieren richtig die innerhalb Events Sammlung Subdokument Teilnehmer.

Das Problem:

ich nur den geänderten Teilnehmer müssen als JSON zurückgegeben werden, und ich bin nicht in der Notwendigkeit des gesamten Arrays Teilnehmer aber ich bin das nicht in der Lage zu erreichen, da ich alle Teilnehmer erhalten, wenn Ich mache console.log(result.participants);

Wie bekomme ich nur das geänderte Filialdokument nach der Abfrage?

Antwort

0

Sie müssen die native JS filter() Methode wie im folgenden verwenden:

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

Dank. Sieht so aus, als ob das der einzige Weg ist (obwohl es ineffizient ist). –

Verwandte Themen