Reputation: 321
I'm trying to fetch more than one document that satisfies a particular criteria from a collection in my MongoDB database. When I use findOne(), it works perfectly fine and returns the first document that follows the criteria, but find() isn't returning all of the documents. I've checked a lot of websites and the documentation but still haven't found good examples of how it is done. This is the current syntax that I'm trying :
db.collection('mycollection').find({someproperty :
somevalue}).then((docs)=>{
// trying to do something with the returned documents 'docs'
}
Also, I'd really prefer a non-mongoose solution, unless this is absolutely impossible using plain MongoDB. I know it's probably easier with mongoose but I want to know the MongoDB implementation.
Upvotes: 0
Views: 31
Reputation: 5137
In the Mongo Docs the find
function returns a cursor
.
A cursor to the documents that match the query criteria. When the find() method “returns documents,” the method is actually returning a cursor to the documents.
I'm guessing you expect an array? You need to use the toArray
function, the docs for this are https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#toarray
Unfortunately it's a callback, no promise implementation so you will need to put the promise in there yourself.
return new Promise((resolve, reject) => db.collection('mycollection')
.find({someproperty : somevalue})
.toArray((err, documents) => resolve(documents)));
Upvotes: 1