代码之家  ›  专栏  ›  技术社区  ›  Hugo Licon

MongoDB/Mongoose查询特定日期之间的文档?

  •  0
  • Hugo Licon  · 技术社区  · 7 年前

    我希望它能在特定日期之间获取文档,我知道我需要使用 $和 接线员,但现在我在用 Querymen 作为MongoDB的中间件,我阅读了文档,但找不到与之相关的任何内容。

    我要做的是:

    router.get('/',
      token({ required: true }),
      query({
        after: {
          type: Date,
          paths: ['fecha'],
          operator: '$gte'
        },
        before: {
          type: Date,
          paths: ['fecha'],
          operator: '$lte'
        }
      }),
      index)
    

    所以我的问题是如何使用$和运算符

    1 回复  |  直到 7 年前
        1
  •  0
  •   Dmitry Shvetsov    7 年前

    你不用用 $and 查询中的运算符。而不是这个:

    {
      $and: [
        { yourDateField: { $lte: '2018-08-09' } },
        { yourDateField: { $gte: '2018-08-03' } },
      ]
    }
    

    你可以:

    {
      yourDateField: {
        $lte: '2018-08-09',
        $gte: '2018-08-03'
      }
    }
    

    所以你可以使用这个模式 槲皮素 :

    const querySchema = {
      after: {
        type: Date,
        paths: ['yourDateField'],
        operator: '$gte'
      },
      before: {
        type: Date,
        paths: ['yourDateField'],
        operator: '$lte'
      }
    };
    

    完整的示例可能如下所示:

    const querymen = require('querymen');
    const app = require('express')();
    
    const querySchema = {
      after: {
        type: Date,
        paths: ['yourDateField'],
        operator: '$gte'
      },
      before: {
        type: Date,
        paths: ['yourDateField'],
        operator: '$lte'
      }
    };
    
    app.get('/', querymen.middleware(querySchema), (req, res) => {
      const { querymen: { query } } = req;
      res.json({ ok: true, query });
    });
    
    app.listen(8000, () => console.log('Up and running on http://localhost:8000'));
    

    如果你仍然怀疑为什么不使用 $和 接线员看 this answer .