Using toArray in MongoDB
In our last tutorial, we query mongodb for all states that starts with the letter “A”. We were using cursors to retrieve and iterate though our records. In this tutorial, we do similarly but using toArray method. We change our code to be …
We call the find() method as before. But this time we don’t store a cursor. We call the toArray() method which builds an array of the returned results. This array is given to us as “docs” in the callback function.
docs is a normal javascript array for which we can use the forEach method to iterate through the array.
We added console.log so that we can see each record in our console…
See that our projection has limited the records to return only the state field and not the rest of the fields. Except for the _id field which is returned by default regardless unless explicitly stated to not return in the projection.
Error: Cannot call method ‘forEach’ of null
But you can not mix excluding and including other fields such as …
var projection = { ‘state’ : 1, ‘high’ : 0 };
otherwise you get the error “Cannot call method ‘forEach’ of null”
This is because the docs object is null. The toArray is not able to build the docs object due to the projection.