简体   繁体   中英

For Loop not working inside Node.js while using mongoose

I am trying fetch records from mongoDB through mongoose

   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.

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 :

[Note : id field is added by default, hence to remove it in select we specifically mention it using -_id. You can remove -_id if you want to maintain ID inside the response document.]

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.

I have used Lean.exec within Mongoose.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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