Mongoose:按日期范围筛选文档返回0个文档



我有这个型号:

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" },
}); 

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

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(),
},
},
};

相关内容

  • 没有找到相关文章

最新更新