FindOne里面保存在for循环中

时间:2017-07-29 02:57:14

标签: node.js mongodb asynchronous

嘿伙计们我正在尝试使用这段代码,而且我非常确定这里涉及MongoDB 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);
                });
     });

我一直试图查看文档,但仍然无法弄明白。

1 个答案:

答案 0 :(得分: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);
    });

});