2016-05-30 6 views
0

私はこのコードを今日作成しましたが、何が問題なのですか?理論的には、findOne()関数はforの各ループに対して働きます。そして、これは何が起こるかではありません。配列にはいくつかの要素があり、私はこれをすべて保存したい。私はNodeJSの初心者ですが、()のループは常に同じですか、そうではありませんか?MongoDBとの間違い - 配列 - ループ

var sType = models.Type; // Model Mongoose 
    var word = ''; // Word 
    var i = 0; 

    for(i = 0; i < arrayData.length; i++){ 
     word = arrayData[i]; // Save the element in word, I made this to try to pass the variable. 
     sType.findOne({ nameType: word }, { _id : 1 }, function(err, type){ 
      console.log(word); // In the console, show me the last element of array x20. 
      if(err) 
       throw err; 
      if(!err && type == null){ 
       var types = new sType({ 
        nameType: word 
       }); 

       types.save(function(err){ 
        if(err) 
         throw err;   
       }); 
      } 
     }); 
    } 

私は変数「言葉」を作成していない場合は、プログラムが間違い「検証エラー:パス 『私を投げる』。必要とされる」NAMETYPEは、

答えて

0

あなたがループ内のメソッドfindOneを使用する場合は、コールバックを待機する必要があり、ライブラリーasync.jsを使用しようと、

ここでは一例です:

async.eachSeries(arrayData, function(data, dataCallback) { 

    sType.findOne({}, {}, function(err, type) { 
    //your code after the findOne method 

    //return to the next element of array 
    dataCallback(); 
    } 
}, function done() { 
    console.log("loop end"); 
});