【问题标题】:Mongoose Query executed in for loop is not being pushed into an empty array after the for loop in finished executing, nodejs在for循环完成执行后,在for循环中执行的Mongoose查询没有被推入空数组,nodejs
【发布时间】:2018-01-27 04:56:24
【问题描述】:

说,我有一个模型,其中包含一组传入的值,

[ { _id: 5a69e13780e4172d514ed906, hobbyname: 'Teaching', __v: 0 },
{ _id: 5a69e1477a40892d6416f906, hobbyname: 'Cricket', __v: 0 }]

var arr = [];
    for(var i=0; i < someModel.length; i++){
    Hobby.find({})
       .then(function(hob){
           arr[i] = someModel[i].hobbyname;
       })
       .catch(function(err){
           console.log(err);
       });
    }
console.log(arr);

目前它的日志记录 arr 为 [],我希望它完成查询执行,将值推送到 arr,然后给我结果。

我已经简化了我的项目场景,只是为了让它易于理解,我是一个新手,需要帮助,在此先感谢。

【问题讨论】:

    标签: javascript arrays node.js mongodb mongoose


    【解决方案1】:

    所有数据处理都应该在回调函数中

       Hobby.find({})
         .then(function(hob){
            console.log(hob);
            //here **hob** already contains the result of Mongo query - it's an array
            //so put your processing code here
         })
         .catch(function(err){
             console.log(err);
         });
    

    如果您想通过 id 或其他条件从 Mongo 捕获数据,您需要在查找查询中设置此类条件 更新: 或者你可以使用async.waterfall获取数据后进行处理

    async.waterfall(
      [
        function(callback) {    
         Hobby.find({})
           .then(function(hob){
              console.log(hob);
              return callback(null, hob);
           })
           .catch(function(err){
               console.log(err);
               return callback(err);
           });
        },
        function(hobbies, callback) {
          //here you get all retrieved hobbies to work on
          //**hobbies** - is result array
          //you may process it here
    
          return callback(null, hobbies);
        }
      ],
      function(err, result) {
        if (err) {
          console.log(err);
    
        }
    
        return next();
      }
    );  
    

    【讨论】:

    • 感谢您的回复,但我想知道如何将 for 循环中的查询结果推送到空数组中。我希望 for 循环等待完整的查询执行,将值一一存储在数组中,然后在数组外打印数组。请帮助我或至少让我知道如何进行回调。
    • 再次 - 执行查询后 - 函数将返回结果数组,其中包含 hob 数组中的所有获取记录,因此您需要将代码用于记录处理而不是我的 cmets加了//here **hob** already contains the result of Mongo query - it's an array //so put your processing code here看看这个综合例子using MongoDB with NodeJS/Express
    • 我想把结果用在外面。就像,当我 console.log(arr); 时,我必须在 for 循环中获取输出过程。
    猜你喜欢
    • 2018-02-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    相关资源
    最近更新 更多