[英]MongoDB: Get all collections in one document
I´ve got in some trouble with Javascript and mongoDB. 我在使用Javascript和mongoDB时遇到了麻烦。 I connected via:
我通过以下方式连接:
var db = mongo.db(config.connectionString, { native_parser: true });
and bind my visitors collection db.bind('visitors');
并绑定我的访问者集合
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)
angular.js:12011 GET http:// localhost:3000 / api / visitors / getAll 400(错误请求)
I thought its something with my api so I tried ...findOne({_id:1},..
and that worked. So did I missed something ? 我用我的api想到了它,于是我尝试了
...findOne({_id:1},..
并且行得通。那我错过了什么吗?
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. 使用
findOne()
测试的原因在于,您是通过{_ id: 1}
对象传递查询的。
The documentation about MongoDB queries in Node.js is here . Node.js中有关MongoDB查询的文档在这里 。
Edit: 编辑:
An example of using .find()
and handling the cursor object in an async way by converting it to an array: 使用
.find()
并通过将其转换为数组以异步方式处理游标对象的示例:
db.visitors.find({}).toArray(function (err, docs) {
if (err) throw err;
console.log(docs);
});
I think you missed the parameters part of the find()
. 我认为您错过了
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(){...});
因此看起来应该像
find({}, function(){...});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.