What is returned from Mongoose query that finds no matches?
Solution 1
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.
Solution 2
If conditions were valid but no matches were found:
find
:err
isnull
,result
is[]
findOne
andfindById
:err
isnull
,result
isnull
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
Related videos on Youtube
Colin
Updated on July 09, 2022Comments
-
Colin almost 2 years
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
andresults
in the callback functioncallback(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
= null
-
Colin almost 11 yearsGuess there is three options ;)
-
Colin almost 11 yearsSo, in
find
its case 1, infindOne
its case 2? -
randunel almost 11 yearsYou can use it like
var query = Model.find();
orvar query = Model.findOne();
Later edit: i just saw your edit, indeed, 3 options :) You got the cases right. -
Lion789 almost 9 yearsWhat are the results if you use .populate?