[英]Querying a range of dates in Mongoose and Node
I have the following User schema:我有以下用户架构:
const User = mongoose.model(
"User",
new mongoose.Schema({
email: String,
password: String,
name: String,
days: [
{
day: Date,
data:
{
average_score: {type: mongoose.Schema.Types.Decimal128, default: 0 }
}
}
]
})
);
In the day field I'm storing the days in ISO format like 2020-12-29T00:00:00.000Z for example.在日期字段中,我以 ISO 格式存储日期,例如 2020-12-29T00:00:00.000Z。 The query is returning all the data instead of returning the data for the days between the Date range.
查询返回所有数据,而不是返回日期范围之间天数的数据。
User.find({ "_id": getUserId(req), "days.day":{
"$gte": new Date("2021-01-02T00:00:00.000Z"),
"$lt": new Date("2021-01-04T00:00:00.000Z")
}},
function (err, result) {
if (err){
res.status(400).send({data: { message: err }});
return;
}
else if(result)
{
res.status(200).send({data: { message: result }});
}
})
The solution that I found to work is:我发现有效的解决方案是:
let itsArray = Array.isArray(req.body.day)
let first = itsArray ? new Date(new Date(req.body.day[0]).toISOString()) : null
let second = itsArray ? new Date(new Date(req.body.day[1]).toISOString()) : null
let theDay = itsArray ? null : new Date(req.body.day)
let now = new Date()
theDay = itsArray ? null : new Date(new Date(theDay).toISOString())
const objectProject = { $project: {
days: {
$filter: {
input: "$days",
as: "index",
cond:{ $eq: [ "$$index.day", theDay ] },
}
}
}}
const arrayProject = { $project: {
days: {
$filter: {
input: "$days",
as: "index",
cond: {$and: [
{ $gte: [ "$$index.day", first ] },
{ $lte: [ "$$index.day", second ] }
]}
}
}
}}
await User.aggregate([
{$match:{_id: ObjectID(getUserId(req))}},
itsArray ? arrayProject : objectProject
])
.project({'days.day':1, 'days.data':1})
.then(result => {console.log(result})
Using project, match and then filter seems to yield the desired results.使用项目、匹配然后过滤似乎可以产生所需的结果。
It seems that the result I wanted required some more advanced mongodb kung-fu:看来我想要的结果需要一些更高级的 mongodb 功夫:
const objectProject = { $project: {
days: {
$filter: {
input: "$days",
as: "index",
cond:{ $eq: [ "$$index.day", theDay ] },
}
}
}}
const arrayProject = { $project: {
days: {
$filter: {
input: "$days",
as: "index",
cond: {$and: [
{ $gte: [ "$$index.day", first ] },
{ $lte: [ "$$index.day", second ] }
]}
}
}
}}
await User.aggregate([
{$match:{_id: ObjectID(getUserId(req))}},
itsArray ? arrayProject : objectProject
])
.project({'days.day':1, 'days.data':1})
.then(result => {console.log(result})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.