2017-07-29 3 views
0

こんにちは、私はこのコードを使用しようとしています。ここでは、MongoDB findOneを含む非同期問題があり、forループを保存していると確信しています。FindOneの内部でのforループの保存

restArray.forEach(function(restArr) 
    { 
     var temp = new Restaurant ({ 
       nameOfRest: restArr.restaurant.name, 
       favoriteFoods:[], 
    }); 
        console.log(restArr.restaurant.name); 
      //Find a restaurant and if it can't find one: 
      //Set up a new one. 
      Restaurant.findOne({nameOfRest: restArr.restaurant.name}).then(function(err,data){ 
        if(err){ 
         console.log("Error in finding."); 
        } 

        else if(!data) 
        { 
         //console.log(temp); 
         temp.save().then(function(err){ 
          if(err) { 
           console.log("Error in saving"); 
          } 
         }); 
        } 
        //console.log(data); 
       }); 
    }); 

私はドキュメントを見ようとしていますが、まだそれを理解できませんでした。

+0

を更新しましたnode.jsの '' async''モジュールを使用できる場合 –

+0

forEachループだけで問題が解決するのでしょうか?forEachループと非同期モジュールの両方が必要ですか? –

+0

forEachはあなたの問題を解決しますが、私たちはそれを同期して実行し、コールバックhell..soを引き起こす可能性があります。私はむしろ '' 'async''モジュールを使用してコードをもっときれいにし、 –

答えて

0

私は約8ヶ月前にノードに溺れ、試行錯誤の傷を持ってそれを証明します。
私はあなたに約束を導入することで、頭痛を軽減できることを願っています。これによりコードは実行可能で、読み取り可能で、競合状態を回避し、が約束しますです。

構文は再フォーマットされています。

const Mongoose = require('mongoose'); 
const Promise = require('bluebird'); // Promise library 

Mongoose.Promise = Promise; // Set mongoose to use bluebird as the promise library. Bluebird comes with a lot of useful promise utilities not found in the stock Promise library. 

let restaurants = ["kfc", "churcheschicken", "chicken and waffles"]; 

let promises = []; 

restaurants.forEach((name, idx, arr) => { 

    promises.push(Mongoose.models.Restaurant.findOne({ "nameOfRest": name })); 

}) 


// handle all errors 
let onAllErrors = function(err){ 
    // do something with errors 
} 

let onDocumentSaved = function(newSavedDocument){ 
    // do something with saved document 
} 


// Run array of promises through this chain. 
Promise.mapSeries(promises, (rest, idx, length) => { 

     //rest will be a model found in your database 

     if (!rest) { //not found, lets create a new restaurant 
      let newRest = new Mongoose.models.Restaurant({ 
       nameOfRest: restaurants[idx], 
       favoriteFoods:[], 
      }) 
      // return items will be found in RESULTS in the next .then chain 
      return newRest.save().then(onDocumentSaved).catch(onAllErrors); 
     } 
    }) 
    .then(RESULTS => { 
     // returned from above 
    }) 
    .catch(onPromiseError)); 

*******あなたはどちらか、物事のこれらの種類を実行するforeachループを使用するか、それが良いだろうしたいcorrect.Ifある*******

var findOrCreate = function(){ 
    console.log(restArr.restaurant.name); 
    //Find a restaurant and if it can't find one: 
    //Set up a new one. 
    Restaurant.findOne({nameOfRest: this.nameOfRest}) 
     .then(exist => { 
      if (!exist) { 
       this.save() 
        .then(result => { 
         console.log(result); 
         //document saved 
        }) 
        .catch(err => { 
         console.log(err); 
        }); 
      } 
     }) 
     .catch(err => { 
      debugger; 
      //reject(err); 
     }); 
} 

restArray.forEach(function(restArr) 
    { 
     var temp = new Restaurant ({ 
       nameOfRest: restArr.restaurant.name, 
       favoriteFoods:[], 

      findOrCreate.call(temp); 
    }); 

}); 
関連する問題