Laakal
Laakal

Reputation: 687

Why does MongoDB/Mongoose find query with null or undefined argument return all docs?

API requests same data from MongoDB with specific parameters. But I don't want to return any docs If query parameter are null or undefined. On the contrary, MongoDB returns all docs. Why and is this normal?

await exampleModel.find({}).lean().exec()        // return all docs. That's okay.
await exampleModel.find(null).lean().exec()      // return all docs. That's weird.
await exampleModel.find(undefined).lean().exec() // return all docs. That's weird.

Upvotes: 1

Views: 2455

Answers (1)

Ionică Bizău
Ionică Bizău

Reputation: 113445

Yes, this is normal. Perhaps MongoDB defaults to an empty filter ({}) when passing null or undefined or not passing a parameter at all (foo.find()). In any case the filter and the projection (the second parameter) are optional:

query: Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document ({}).

projection: Specifies the fields to return in the documents that match the query filter. To return all fields in the matching documents, omit this parameter.

If you want to not return anything if the query is null or undefined you can build it like this:

const results = query ? await exampleModel.find(query).lean.exec() : []        

Upvotes: 2

Related Questions