【问题标题】:Query all types of a document field or a specific type with mongodb使用 mongodb 查询文档字段的所有类型或特定类型
【发布时间】:2021-07-26 02:28:19
【问题描述】:

所以,我需要根据请求查询在数据库中查找文档,但如果没有指定,我想查找所有文档,所以我做了这样的事情(使用 mongoose-paginate-v2):

    // query params
    const page = parseInt(req.query.page) || 1;
    const category = req.query.category || '*';
    const type = req.query.type || '*';

    // query posts
    let posts = await Post.paginate({
        postCategory: category,
        postType: type
    }, {
        page: page,
        limit: 10
    });

这会返回一个空数组,可能是因为 mongodb 查询没有任何意义。但是如果没有指定类别和类型,有没有办法对每个文档进行查询呢?

【问题讨论】:

    标签: javascript node.js mongodb mongoose nosql


    【解决方案1】:

    默认页面应为0 而不是1。仅使用发送的数据创建 filter 对象。将paginate 更改为find

    // query params
    const page = parseInt(req.query.page || 0);
    let filter = {};
    if(req.query.category) filter.postCategory: req.query.category;
    if(req.query.type) filter.postType: req.query.type;
    
    // query posts
    let posts = await Post.find(filter, { page: page });
    

    【讨论】:

    • 它不起作用,它只是返回一个空的文档数组
    • 我更新了我的答案,你可以再试一次吗?它现在应该可以工作了。
    【解决方案2】:

    使用 ?? (空值合并)运算符而不是 ||您甚至可以将 req.query.page 设置为 0。 你的代码应该是这样的

    const page = parseInt(req.query.page) ?? 1;
    const query = {}
    if(req.query.category) {query.category = req.query.category}
    if(req.query.type) {query.category = req.query.type}
    
    // query posts
    let posts = await Post.paginate(query, {
      page: page,
      limit: 10
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多