Reputation: 2174
I was reading How to use MongoDB with promises in Node.js? when I saw that in the first answer they say that if I pass no callback, mongo driver will return me a promise. It worked for 'connect' but it didn't work when I tried:
db.collection('myCollection').find().then((docs)=>{console.log(docs)})
I got:
MongoDB error: TypeError: db.collection(...).find(...).then is not a function
I tried to read the documentation for find()
at http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#find and I can see some examples there that does things like this:
collection.find({}).explain().then(function(docs) {
test.ok(docs != null);
db.close();
});
this is a Promise for find but it has this explain()
thing. What is it? Also, why there is no mention of promises in this API? There's also another line that does:
collection.insertMany([{a:1}, {a:2}, {a:3}], {w:1}).then(function(result) {
which is also a promise.
So, how to use promises with find()?
Also, why this documentation won't tell the return values of anything? Neither the arguments I can use...
Upvotes: 0
Views: 1363
Reputation: 3747
What you are looking for is toArray()
, which works like you want (callback inside, or promise returned if not callback)
db.collection('...').find().toArray()
.then(function(docs) {
// =)
});
This is because db.collection('..').find()
returns a cursor, not a promise.
This behavior is intended because "find as a whole" is not the only pattern that can be used (ie. streams are allowed).
Upvotes: 3