MongoDB Node findone how to handle no results?

node.jsMongodb

node.js Problem Overview


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..)

node.js Solutions


Solution 1 - node.js

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
	}
}

Solution 2 - node.js

All of these answers below are outdated. findOne is deprecated. Lastest 2.1 documentation proposes to use

find(query).limit(1).next(function(err, doc){
   // handle data
})

Solution 3 - node.js

Simply as:

collection.findOne({query}, function(err, result) {
    if (!result) {
        // Resolve your query here
    }
}

Solution 4 - node.js

nowadays - since node 8 - you can do this inside an async function:

async function func() {
  try {
    const result = await db.collection('xxx').findOne({query});
    if (!result) {
      // no result
    } else {
      // do something with result
    }
  } catch (err) {
    // error occured
  }
}

Solution 5 - node.js

If result is null then mongo didn't find a document matching your query. Have tried the query from the mongo shell?

Solution 6 - node.js

collection.findOne({query}, function(err, result) {
   if (err) { /* handle err */ }

   if (result.length === 0) {
    // we don't have result
   }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTarangView Question on Stackoverflow
Solution 1 - node.jsjmar777View Answer on Stackoverflow
Solution 2 - node.jsStepan YakovenkoView Answer on Stackoverflow
Solution 3 - node.jssospedraView Answer on Stackoverflow
Solution 4 - node.jsuser2779653View Answer on Stackoverflow
Solution 5 - node.jsMartinView Answer on Stackoverflow
Solution 6 - node.jsparkerprojectView Answer on Stackoverflow