【发布时间】:2021-04-25 02:02:40
【问题描述】:
$match: {
date: { $gte: fromDate, $lte: toDate },
if (userId) {
user: userId
}
},
我仅在提交userId 时才尝试匹配用户。最好的方法是什么。
【问题讨论】:
标签: javascript mongodb mongoose aggregate
$match: {
date: { $gte: fromDate, $lte: toDate },
if (userId) {
user: userId
}
},
我仅在提交userId 时才尝试匹配用户。最好的方法是什么。
【问题讨论】:
标签: javascript mongodb mongoose aggregate
您可以使用mongoose query builder,根据您的条件管理聚合阶段,
// INITIALIZE
let p = YourSchemaModel.aggregate();
// DATE FILTER
p.match({ date: { $gte: fromDate, $lte: toDate } });
// USER ID FILTER
if (userId) p.match({ user: userId });
// RESULT
let result = await p.exec();
如果两者都在一起,聚合将自动合并
$match阶段!
第二个选项:
let result = await YourSchemaModel.aggregate().match(
Object.assign(
{ date: { $gte: fromDate, $lte: toDate } },
userId ? { user: userId } : {}
)
).exec();
【讨论】: