Reputation: 1855
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:
err
= null, results
= []err
= null, results
= nullerr
= error document, results
= nullUpvotes: 46
Views: 26015
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
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
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