我有以下应用。 需要(FreeCodeCamp)返回url和_id和用户名匹配查询的日期运动和时间段(持续时间)的集合。
我尝试过的事情如下。
$match
一起使用汇总以在查询中找到_id。$unwind
展开数据数组。网址:
http://localhost:3000/api/exercise/log21?id=eUyhCDgMB&start=31 December 2018&end=22 December 2018&limit=2
let iniate = new Date(req.query.start);
let one = moment(iniate).format("YYYY-MM-DDT00:00:00.000") + "Z";
let date1 = new Date(one);
console.log(date1);
console.log(typeof(date1));
let iniate1 = new Date(req.query.end);
let two = moment(iniate1).format("YYYY-MM-DDT00:00:00.000") + "Z";
let date2 = new Date(two);
console.log(date2)
console.log(typeof(date2))
app.get('/api/exercise/log21', (req, res) => {
array.aggregate([{
$match: {
'_id': req.query.id
}
}, {
$unwind: "$data"
}]).then(doc => {
res.send(doc)
}).catch(e => {
res.send(e);
})
})
JSON返回
[{
"_id": "eUyhCDgMB",
"username": "Donald Duck",
"data": {
"description": "walking",
"duration": 2,
"date": "2019-01-01T00:00:00.000Z"
},
"__v": 0
},
{
"_id": "eUyhCDgMB",
"username": "Donald Duck",
"data": {
"description": "Mountain Biking",
"duration": 3,
"date": "2019-01-01T00:00:00.000Z"
},
"__v": 0
},
{
"_id": "eUyhCDgMB",
"username": "Donald Duck",
"data": {
"description": "Reading",
"duration": 3,
"date": "2018-12-31T00:00:00.000Z"
},
"__v": 0
}
]
我需要过滤掉所有与url中的查询不匹配的日期,并返回与用户名,id,描述,持续时间和匹配日期匹配的查询。
在我的代码localhost 3000中显示。
为了从字符串到日期对象获取日期查询,我正在使用moment.js。
如我的代码中所示,其中包含date1
和date2
变量。
我正在尝试将$gte
设置为date1
,将$lte
设置为$end=date2
如果限制设置为小于返回的日期,则需要返回在url中设置的日期数量。限制示例为2。仅返回两个匹配的日期值。
答案 0 :(得分:0)
我终于找到了一种设置匹配日期或文档日期限制的方法。我包括以下代码。 我包含以下代码。
app.get('/api/exercise/log',(req,res)=>{
array.findById({_id:req.query.id},(err,data)=>{
let iniate = new Date(req.query.start);
let one = moment(iniate).format("YYYY-MM-DDT00:00:00.000") + "Z";
let date1 = new Date(one);
console.log(date1);
console.log(typeof(date1));
let iniate1 = new Date(req.query.end);
let two = moment(iniate1).format("YYYY-MM-DDT00:00:00.000") + "Z";
let date2 = new Date(two);
console.log(date2)
console.log(typeof(date2))
let myLength;
if(req.query.start === undefined && req.query.end === undefined && req.query.limit === undefined && req.query.id !== undefined){
myLength = data.data.length;
array.aggregate([
{ $match: {_id: req.query.id}}]).then(data =>{
res.send({count:myLength,data})
})
}
else if(req.query.start !== undefined && req.query.end !== undefined && req.query.limit !== undefined && req.query.id !== undefined){
array.aggregate([
{ $match: {_id: req.query.id}},
{ $unwind: '$data'},{$match : {"$and" : [{"data.date" :{$gte : date1} },
{"data.date" :{"$lte" : date2}}]}}]).limit(Number(req.query.limit)).then(data =>{
if(data.length >= Number(req.query.limit)){
res.send(data)
}else{
return res.send({error:"Document do not match limit requested"})
}
})
}
})
})
这最终返回了project的必需参数,这对于完成我的Free Code Camp项目是必需的。使用以下链接stackoverflow question how to query data inside an array of the collection using mongoose