Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 792
Colin Avatar asked Aug 13 '13 16:08

Colin


People also ask

What does Mongoose find return?

find() 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.

What does Mongoose Exec return?

exec() function returns a promise, that you can use it with then() or async/await to execute a query on a model "asynchronous".

Does Mongoose return promise?

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.

What is callback in Mongoose?

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.


2 Answers

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.

like image 82
randunel Avatar answered Sep 18 '22 09:09

randunel


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

like image 30
cute_ptr Avatar answered Sep 21 '22 09:09

cute_ptr