【问题标题】:Mongoose: Filtering documents by date range returns 0 documentsMongoose:按日期范围过滤文档返回 0 个文档
【发布时间】:2022-02-21 14:57:05
【问题描述】:

我有这个模型:

const HistorySchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "users",
  },
  category: {
    type: String,
    enum: category_enum,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

所以一个文档可以是:

{
    "_id": "60ddad447b0e9d3c4d4fd1f1",
    "user": "60dc8118118ea36a4f3cab7d",
    "category": "LOGIN",
    "date": "2021-03-02T00:00:00.000Z",
    "__v": 0
},

我正在尝试通过以下方式获取给定年份发生的事件:

const getEventsOfYear = async (year) => {
  let response = {
    events_of_year_per_user: null,
  };

  const start_date_of_the_year = moment(year);
  const end_date_of_the_year = moment(year).endOf("year");
  const filter_stage = {
    $match: {
      date: {
        $gte: start_date_of_the_year,
        $lte: end_date_of_the_year,
      },
    },
  };
  const pipeline = [filter_stage];
  const history_events_with_aggregate = await History.aggregate(pipeline);
  response.events_of_year_per_user = history_events_with_aggregate;
  return response;
};

问题是这总是返回一个空数组:

{
    "events_of_year_per_user": []
}

知道我做错了什么吗?


编辑 1: 我什至尝试使用另一个模型和直接日期输入而不是使用时刻,但结果仍然相同:

const filter_stage = {
  $match: {
    date: {
      $gte: "2022-01-01",
      $lte: "2022-12-30",
    },
  },
};

const pipeline = [filter_stage];
const history_events_with_aggregate = await userModel.aggregate(pipeline);

但是,使用find 可以:

  const history_events_with_aggregate = await userModel.find({
    date: { $gte: "2022-01-01", $lte: "2022-12-30" },
  }); 

【问题讨论】:

    标签: mongodb mongoose aggregation-framework momentjs


    【解决方案1】:

    这就是我解决问题的方法:

      const filter_stage = {
        $match: {
          date: {
            $gte: new Date("2022-01-01"),
            $lte: new Date("2022-12-30"),
          },
        },
      };
    

    如果你想使用moment:

     const start_date_of_the_year = moment(year);
     
      const end_date_of_the_year = moment(year).endOf("year");
      
      const filter_stage = {
        $match: {
          date: {
            $gte: new Date(start_date_of_the_year),
            $lte: new Date(end_date_of_the_year),
          },
        },
      };
    

    您也可以这样做:

      const today = moment().startOf("day");
      const filter_stage = {
        $match: {
          user: ObjectId(user_id),
          date: {
            $gte: today.toDate(),
            $lte: moment(today).endOf("day").toDate(),
          },
        },
      };
    

    【讨论】:

      猜你喜欢
      • 2020-03-22
      • 2019-02-19
      • 2017-04-17
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      • 2019-07-13
      • 2014-04-12
      • 1970-01-01
      相关资源
      最近更新 更多