2016-08-09 11 views
0

Ich möchte Mails eines Benutzers mit seiner ID suchen. Aber ich habe ein Problem, weil die Mungo-Funktion asynchron ist.Verwenden Sie Wert in mongoose Bereich Funktion

Mail.find({receiver_id: '#id#'}, function(err, mails) { 
    var result = []; 
    var count = 0; 
    if (mails.length > 0) { 
     for (m of mails) { 
      User.findById(m.sender_id, function(err, user) { 
       if (user) { 
        result.push({ 
         id: m._id, 
         title: m.title, 
         body: m.body 
        }); 
        if (++count == mails.length) { 
         res.json({success: true, data: result}); 
        } 
       } 
      }); 
     } 
    } else { 
     res.json({success: false, error: 'Cannot find any email'}); 
    } 
}); 

Das Problem ist, als ich mein Ergebnis bekam, waren alle Mails die gleichen. Wie ich verstand, weil User.findById eine Asynchron-Funktion ist, so, wenn ich in dieser Funktion m verwenden, stellt der m immer das letzte Kind von Mail.

ich herausgefunden habe, dass, wenn ich einige Variablen als zweiten param von findById Funktion übergeben, sollte es funktionieren:

User.findById(m.sender_id, {id: m._id, title: m.title, body: m.body}, function(err, user) { 
    if (user) { 
     result.push({id, title, body}); 
     if (++count == mails.length) { 
      res.json({success: true, data: result}); 
     } 
    } 
}); 

sondern weil mein Dokument nicht nur drei Felder hat, so denke ich, es gibt eine andere bessere Lösung.

Wie kann ich es richtig machen? Vielen Dank !

+0

Verwenden Sie dieses Modul mit Ihren E-Mail-Objekten. https://github.com/caolan/async –

Antwort

1
var async = require("async"); 
var yourResult = []; 
async.each(mails, function(mailObj, done){ 
    User.findById(mailObj.sender_id, function(err, user) { 
     //add data into result. call async callback function. 
     done(); 
    }) 
}, function(err){ 
    //final callback write res here 
    result.push(yourResult); 
    res.json({success: true, data: result}); 
}); 

Async-Dokumentation hier. http://caolan.github.io/async/index.html Hoffe, das hilft.

+0

Genau was ich brauche. Vielen Dank ! –

Verwandte Themen