Colin
Colin

Reputation: 1855

What is returned from Mongoose query that finds no matches?

I'm a little confused reading the Mongoose documentation.

If I run a query in mongoose which matches no documents in the collection, what are the values of err and results in the callback function callback(err, results)? I just don't know what Mongoose considers an "error". As a mathematician, returning the empty set (i.e. results array empty) seems perfectly valid and shouldn't be an "error" - the query executed fine, there was just no matching documents. On the other hand, some may consider it an "error". From mongoose docs, either:

  1. err = null, results = []
  2. err = null, results = null
  3. err = error document, results = null

Upvotes: 46

Views: 26015

Answers (3)

sh15h4nk
sh15h4nk

Reputation: 29

If using .find(),
The handy way would be

models.<your collection name>.find({ _id: `your input` }).then(data => {
    if (data.length == 0) return // throw your error to the console;
});

Upvotes: 1

cute_ptr
cute_ptr

Reputation: 1203

If conditions were valid but no matches were found:

  • find: err is null, result is []

  • findOne and findById: err is null, result is null

However, if some condition was invalid (e.g. field is string but you pass an object, or you pass an invalid _id)

For all three: err is {..}, result is undefined

Upvotes: 10

randunel
randunel

Reputation: 8945

It depends on the query. If it is a find, then results == []. If it is a findOne, then results == null. No errors if everything else is ok.

Upvotes: 59

Related Questions