Marvin Heilemann Marvin Heilemann - 6 months ago 34
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
db.bind('visitors');
. So after I tried to get all documents in there with that line:

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


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
...findOne({_id:1},..
and that worked. So did I missed something ?

Answer

Yes it is wrong. It should be:

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

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.

Edit:

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;
    console.log(docs);
});