简体   繁体   English

使用猫鼬时,For Loop在Node.js中不起作用

[英]For Loop not working inside Node.js while using mongoose

I am trying fetch records from mongoDB through mongoose 我正在尝试通过mongoose从mongoDB获取记录

   router.route('/testaa')
     .get(function(req,res){
         fisSite.find(function(err, retVal) {
         var x = [];
         for(var i =0;i<retVal.length;i++){
         x.push(retVal[i].site);
        }
          res.json(x)
      });

   })

The above code is giving undefined values. 上面的代码给出了未定义的值。

undefined
undefined
undefined
.....

Please help to run the for loop inside node.js so that i can use extract data from array. 请帮助在node.js内运行for循环,以便我可以使用从数组中提取数据。

Currently what you are doing is you are getting all the document fields and then using only one from it. 当前,您正在执行的操作是获取所有文档字段,然后仅使用其中的一个。 You can optimize the query using select method which will only retrieve particular field only rather than all fields : 您可以使用select方法优化查询,该方法将仅检索特定字段,而不检索所有字段:

[Note : id field is added by default, hence to remove it in select we specifically mention it using -_id. [注意:id字段是默认添加的,因此要在选择中将其删除,我们特别使用-_id来提及它。 You can remove -_id if you want to maintain ID inside the response document.] 如果要在响应文档中保留ID,则可以删除-_id。]

fisSite.find({}).select('site -_id').exec(function(err, docs)){

    if(err){
        return res.json({ status : false, message : 'Error Occured.'} );
    }
    else if(!docs){
        return res.json({ status : false, message : 'No documents found.'} );
    }
    else{
        return res.json({ status : success, message : 'Documents found.', data : docs} );
    }
}

Imagine you have 10 fields in each document and find results 100 documents, you only need site field from those 100 documents,however unnecessarily you are calling remaining 900 fields. 假设每个文档中有10个字段,并找到100个结果文档,您只需要这100个文档中的site字段,但是不必要地调用其余的900个字段。

I have used Lean.exec within Mongoose. 我在Mongoose中使用了Lean.exec。

 router.route('/site')
    .get(function(req,res){
    fisSite.find().lean().exec(function(err, retVal) {
    var x = [];
             for(var i =0;i<retVal.length;i++){
             x.push(retVal[i].site);
            }
              res.json(x)
        })
         });

Try to add an empty search query to select all documents 尝试添加一个空的搜索查询以选择所有文档

Try to change 尝试改变

From this: 由此:

fisSite.find(function(err, retVal) 

To this: 对此:

fisSite.find({}, function(err, retVal) 

Also try to do a console.log(retVal) to check if your find actually returns any values. 另外,尝试执行console.log(retVal)来检查您的发现是否实际上返回了任何值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM