API 使用特定参数从 MongoDB 请求相同的数据。但如果查询参数为空或未定义,我不想返回任何文档。相反,MongoDB 返回所有文档。为什么这是正常的?
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.
最佳答案
是的,this is normal 。当传递 null
或 undefined
或根本不传递参数时 (foo.查找()
)。在任何情况下,filter
和 projection
(第二个参数)都是可选的:
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.
如果您不想在查询为空或未定义时返回任何内容,您可以像这样构建它:
const results = query ? await exampleModel.find(query).lean.exec() : []
关于node.js - 为什么 MongoDB/Mongoose 查找带有 null 或未定义参数的查询会返回所有文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59246925/