【问题标题】:Mistake with MongoDB Queries - Arrays - Loop ForMongoDB 查询的错误 - 数组 - 循环
【发布时间】:2016-05-31 09:07:22
【问题描述】:

我今天编写了这段代码,但我不知道有什么问题?理论上,findOne() 函数应该为 for() 的每个循环工作。这不是发生的事情。在数组中有几个元素,我想保存所有这些。我是 NodeJS 的新手,但是 for() 的循环总是一样的,还是不一样?

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

如果我不创建变量 'word',程序会抛出一个错误'Validation Error: Path 'nameTYpe' is required。'

【问题讨论】:

    标签: arrays node.js mongodb mongoose


    【解决方案1】:

    如果在循环中使用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");
    });
    

    【讨论】:

      猜你喜欢
      • 2018-05-15
      • 2020-01-21
      • 2017-01-15
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      相关资源
      最近更新 更多