修改对象中的日期,以便在猫鼬中进行聚合$match查询



我将此对象发送到node.js应用程序中的控制器:

var req.body = {
"startDate": {
"$gte": "1111-11-11T00:00:00.000Z",
"$lte": "2017-08-17T00:00:00.000Z"
}
}

我想要一个函数,它将在此对象的startDate键上运行并给我以下输出:

var req.body = {
"startDate": {
"$gte": new Date("1111-11-11T00:00:00.000Z"),
"$lte": new Date("2017-08-17T00:00:00.000Z")
}
}

我需要此类型对象的原因是我使用mongoose通过aggregate发送查询,$match使用此函数发送mongoDB

var mongoose = require('mongoose');
var Activity = mongoose.model('Activity');
mongoose.set('debug', true);
var sendJSONresponse = function(res, status, content) {
res.status(status);
res.json(content);
}; 
module.exports.readOther = function (req, res){
Activity
.aggregate([
{$match: req.body }
])
.exec(function(err, output) {
sendJSONresponse(res, 200, output);
});
};

mongoose要求new Date(指定日期类型,因此,不会返回应用了原始对象的文档。mongoose现在发送到服务器的查询(为便于阅读而设置了格式(为:

Mongoose: activity.aggregate([ 
{ '$match': 
{ 
startDate: { '$gte': '1111-11-11T00:00:00.000Z', '$lte': '2017-08-17T00:00:00.000Z' }
}, 
], {})

我已经尝试了以下内容来修改对象,但它只是将其转换为实际日期,mongoose无法正确处理

Object.keys(req.body.startDate).map(function (key) {
    req.body.startDate[key] = eval(new Date( req.body.startDate[key] ));
    return req.body.startDate;
  });

请帮助我使用请求的功能或建议另一种允许我查询日期范围的方法。

正如@dnickless在评论中所说,我需要插入

req.body.startDate.$gte = new Date(req.body.startDate.$gte)
req.body.startDate.$lte = new Date(req.body.startDate.$lte)

在我mongoose查询之前。

最新更新