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 ?
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);
});
I think you missed the parameters part of the find()
. Even if you don't want to look for something specific you have to pass an empty object in the parameters part. So it should look like find({}, function(){...});
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.