node.js - 为什么 MongoDB/Mongoose 查找带有 null 或未定义参数的查询会返回所有文档?

标签 node.js mongodb mongoose nosql

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 。当传递 nullundefined 或根本不传递参数时 (foo.查找())。在任何情况下,filterprojection(第二个参数)都是可选的:

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/

相关文章:

node.js - 如何在 MongoDB 和 Node 的另一个集合中引用 ObjectID?

node.js - 使用 Handlebars 比较迭代值

node.js - NestJS Views Not gettings 添加到 Dist

javascript - Promise 链如何断言哪个值来自哪个返回值?

javascript - 尽管存在不安全,但 meteor 更新访问被拒绝

json - 计算数组中多个项目的出现次数

javascript - 使用 node.js 套接字客户端向sails.js (0.11.x) 发送事件

mongodb - 如何在 MongoDB 3.4.10 中获取用于聚合的 executionStats?

javascript - 在继续之前等待异步函数的响应?

javascript - 如何在 mongoose 中正确嵌入文档?