Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Node findone how to handle no results?

Im using the npm mongodb driver with node.

I have

collection.findOne({query}, function(err, result) {     //do something } 

The problem is say I dont have any results, err is still null whether I find a result or don't. How would I know that there were no results found with the query?

I've also tried

info = collection.findOne(.... 

But the info is just undefined (it looked asynchronous so I didn't think it was the way to go anyway..)

like image 608
Tarang Avatar asked May 11 '12 12:05

Tarang


People also ask

What does MongoDB findOne return if not exists?

findOne done not return cursor but single document. "Find" returns cursor. In case "findOne({"query"}) " is not able to fins any matched document then it returns "null".

What does findOne return MongoDB?

The findOne() method finds and returns one document that matches the given selection criteria. If multiple documents satisfy the given query expression, then this method will return the first document according to the natural order which reflects the order of documents on the disk.

How does findOne work in MongoDB?

MongoDB findOne() method returns only one document that satisfies the criteria entered. If the criteria entered matches for more than one document, the method returns only one document according to natural ordering, which reflects the order in which the documents are stored in the database.

Does findOne return promise?

Another way is to get Promise in findOne , as this doc said, . exec() gives you a fully-fledged promise. Even with Promise , to meet you requirement, the result could be returned through callback function.


1 Answers

Not finding any records isn't an error condition, so what you want to look for is the lack of a value in result. Since any matching documents will always be "truthy", you can simply use a simple if (result) check. E.g.,

collection.findOne({query}, function(err, result) {     if (err) { /* handle err */ }      if (result) {         // we have a result     } else {         // we don't     } } 
like image 52
jmar777 Avatar answered Oct 03 '22 08:10

jmar777