【问题标题】:Why does MongoDB/Mongoose find query with null or undefined argument return all docs?为什么 MongoDB/Mongoose 查找带有 null 或未定义参数的查询会返回所有文档?
【发布时间】:2020-04-02 10:35:25
【问题描述】:

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.

【问题讨论】:

    标签: node.js mongodb mongoose nosql


    【解决方案1】:

    是的,this is normal。也许 MongoDB 在传递 nullundefined 或根本不传递参数 (foo.find()) 时默认使用空过滤器 ({})。在任何情况下,filterprojection(第二个参数)都是可选的:

    query: 使用查询运算符指定选择过滤器。要返回集合中的所有文档,请省略此参数或传递一个空文档 ({})。

    projection: 指定要在匹配查询过滤器的文档中返回的字段。要返回匹配文档中的所有字段,请省略此参数。

    如果您不想在查询为 null 或未定义的情况下返回任何内容,您可以像这样构建它:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 2016-01-09
    • 2020-02-19
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多