Marvin Heilemann Marvin Heilemann - 4 months ago 29
AngularJS Question

MongoDB: Get all collections in one document

I´ve got in some trouble with Javascript and mongoDB. I connected via:

var db = mongo.db(config.connectionString, { native_parser: true });

and bind my visitors collection
. So after I tried to get all documents in there with that line:

db.visitors.find(function (err, visitors) {
if (err) deferred.reject( + ': ' + err.message);

So everything looks fine for me. But I get this error every time:

angular.js:12011 GET http://localhost:3000/api/visitors/getAll 400
(Bad Request)

I thought its something with my api so I tried
and that worked. So did I missed something ?


Yes it is wrong. It should be:

db.visitors.find({}, function (err, visitors) {
   if (err) deferred.reject( + ': ' + err.message);

The parameters are:

collection.find(query[[[, fields], options], callback]);

It expects a query first then a callback and you're providing the callback in first place.

Your test with findOne() works because you're passing in a query via the {_ id: 1} object.

The documentation about MongoDB queries in Node.js is here.


An example of using .find() and handling the cursor object in an async way by converting it to an array:

db.visitors.find({}).toArray(function (err, docs) {
    if (err) throw err;