如何查询“any"在 MongoDB 中使用 Mongoose? [英] How to query "any" in MongoDB using Mongoose?

查看:55
本文介绍了如何查询“any"在 MongoDB 中使用 Mongoose?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在网上搜索,但找不到使用 Mongoose 在我的 MongoDB 中进行查询的正确方法.

I'm searching the web and can't find the right way to make a query in my MongoDB using Mongoose.

如果我收到参数,我想执行一个查询:

I want to perform a query if I receive the parameter:

async list(req, res) {
    const { page = 1, limit = 10, status = "" } = req.query;

    const orders = await Order.paginate(
      { status },
      {
        page: parseInt(page),
        limit: parseInt(limit),
        populate: { path: "user", select: "firstName lastName" }
      }
    );
    return res.send(orders);
  }

例如,如果 URL 中未提供状态,我想返回所有文档,如果我提供状态,则仅返回匹配的文档.

So for example, if status is not provided in the URL, I want to return all documents, and if I provide the status, return only the ones that match.

如果我通过了状态,我可以实现我正在寻找的东西,但是如果我没有通过状态,我将无法返回所有文件.我尝试使用 ""undefinednull,但它们都不起作用.

I can achieve what I'm looking for if I pass a status, but I can't return all documents if I don't pass a status. I tried with "", undefined and null, but none of them worked.

我也认为我接近它的方式不是最好的,因为我必须在 const { page = 1, limit = 10, status = "" } = req.query; 所有可能的查询参数.

I also think the way I'm approaching it is not the best, because I'll have to declare in const { page = 1, limit = 10, status = "" } = req.query; all possible query parameters.

我该如何处理?

PS:我正在使用 mongoose-paginate,但他们将 query 文档重定向到 MongoDB 文档,所以我认为它是相同的.

PS: I'm using mongoose-paginate, but they redirect the query documentation to the MongoDB documentation, so I assume it's the same.

提前致谢!

推荐答案

简单的解决方案.我可以使用 ES6 的扩展操作来完成它:

Simple solution. I could accomplish it using the spread operation of ES6:

async list(req, res) {
    const { page = 1, limit = 10 } = req.query;

    let filters = req.query;
    filters = { ...filters, page: undefined, limit: undefined };

    const orders = await Order.paginate(
      { ...filters },
      {
        page: parseInt(page),
        limit: parseInt(limit),
        populate: { path: "user", select: "firstName lastName" }
      }
    );
    return res.send(orders);
  }

这确保了 undefined 对象不会成为查询的一部分

This ensures that undefined objects won't make part of the query

这篇关于如何查询“any"在 MongoDB 中使用 Mongoose?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆