basickarl
basickarl

Reputation: 40522

Mongo native driver toArray() on limit(1)?

According to the documentation the official way to retrieve one document via a Promise is .find().limit(1).toArray() according to the examples here: https://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find

I find it annoying that they have forced a single result when returning a Promise into an array. Unlike the following method find().limit(1).next(function(err, doc){}) which returns the single document. Anyway around this, or is it just to adapt?

Also, findOne is depreciated here https://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne and states the following should be used: find().limit(1).next(function(err, doc){}). However here https://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find it states in the examples to use then().

So, should I use next() or then()?

Upvotes: 2

Views: 1076

Answers (1)

cow
cow

Reputation: 398

You can use find().limit(1).toArray().then(arrs =>{return arrs[0] || null }); if you want to return single object;

collection.find() query all match document return a array object;

Upvotes: 4

Related Questions