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
= nullfind() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries. You don't instantiate a Query directly, Customer.
exec() function returns a promise, that you can use it with then() or async/await to execute a query on a model "asynchronous".
While save() returns a promise, functions like Mongoose's find() return a Mongoose Query . Mongoose queries are thenables. In other words, queries have a then() function that behaves similarly to the Promise then() function. So you can use queries with promise chaining and async/await.
All callbacks in Mongoose use the pattern: callback(error, result) . If an error occurs executing the query, the error parameter will contain an error document, and result will be null. If the query is successful, the error parameter will be null, and the result will be populated with the results of the query.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With