MongoDB Node findone how to handle no results?
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
}
}
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
})