【发布时间】: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