2017-07-29 89 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

你是正確。如果要運行這些類型的東西要麼使用foreach循環或者它會更好如果你可以使用node.js的'''async'''模塊 –

+0

單獨的forEach循環能解決我的問題還是需要forEach循環和異步模塊? –

+0

forEach將解決你的問題,但我們不會假設它在同步運行,並可能導致回調地獄..所以我寧願使用''''async'''模塊,這將使我的代碼更清潔和eaiser –

回答

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

*******修訂*******

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

});