Reputation: 165
Im trying to get iterate the results array variable.
I am able to get the array values inside the function, but when i try to log it outside it shows null.
Wen i googled few posts, i see that forEach was not recommended, suggested was for loop, i tried even that and i get null for result.
What is the issue in cursor.forEach()...
router.get('/getlist', function(req, res, handleError) {
client.connect('mongodb://localhost', function(err, client) {
if (err) throw err;
var db = client.db('angular-demo');
var collection = db.collection("api_details");
var query = {};
var cursor = collection.find(query);
var results = new Array();
var results = cursor.forEach(
function(result) {
return result;
console.log("insert")
console.log(results);
}
);
console.log("append")
console.log(results); //results here shows null
});
});
Log result:
append
[]
insert
[ { _id: 5a6867c8e54f6120709eabc5,
app_id: 'CaseRegistration',
description: 'API to register cases in the system',
cost_per_usage: '0.5',
__v: 0 } ]
insert
[ { _id: 5a6867c8e54f6120709eabc5,
app_id: 'CaseRegistration',
description: 'API to register cases in the system',
cost_per_usage: '0.5',
__v: 0 },
{ _id: 5a6867fde54f6120709eabc6,
app_id: 'CheckCreation',
description: 'CREs create the case with minimal data and assigns it to case initiation team to create checks',
cost_per_usage: '1',
__v: 0 } ]
Upvotes: 2
Views: 485
Reputation: 8070
If you want to grab results from find
you can use toArray
cursor.toArray(function (error, documents) {
console.log(documents)
})
// or
cursor.toArray().then(function (documents) {
console.log(documents)
})
// or in async function
const documnets = await cursor.toArray()
or if you need to transform them somehow use map
Upvotes: 1
Reputation: 8910
It's not relevant if you use forEach
or for
loop in this case. The results
variable isn't being populated because you're trying to populate it with the return result from the forEach which doesn't return anything useful.
What you want to do, is just iterate over the results, and fill the results
array while iterating.
Something more like this :
var results = [];
cursor.forEach(
function(result) {
results.push(result);
}
);
console.log(results); // This should be populated now
Upvotes: 0