使用日期每周和每月查找数据

时间:2018-03-15 07:40:00

标签: node.js mongodb mongoose

我是节点js的新手,我需要每天查找数据, 每周和每月,但我不知道如何做到这一点? 目前我发现今天的数据。还需要查找当前周数据和当月数据。 我不知道怎么做,请你帮忙。

exports.getData = function(req,res)
{
getMyData().then(function(data){
    res.status(200).json({
        msg:'true',
        data: data
    });
}).catch(function(err){
    res.status(401).json({
        msg:'Not Logged In',
        error: err
    });
});
function getMyData(){
    return new Promise(function(resolve,reject){
        var token = req.headers['x-access-token'];
        if (!token)
        return reject({'msg':'No Token'});
        jwt.verify(token,config.secret,function(err,decode){

            if(err)
            {
                reject({'msg':'Failed to authenticate token.'});
            } 
            else{

                var start = new Date();
                start.setHours(0,0,0,0);
                var end = new Date();
                end.setHours(23,59,59,999);

                Data.find({userId: decode.id,created: {$gte: start, $lt: end}},function(err,data){
                    if(err){
                        reject(err);
                    }
                    else
                    {
                        resolve(data);
                    }
                });
            } 
        });
    });
  }
}

这是我的架构

var DataSchema = new Schema({
userId: {
    type: String,
    required: 'Kindly enter your Report'
},data: {
    type: String,
    required: 'Kindly enter your Report'
},
created:{
    type:Date,
    default:Date.now
}
});

1 个答案:

答案 0 :(得分:1)

您可以根据node.js中的不同条件调用查询查询。

var today = new Date().setHours(0, 0, 0, 0);
var first = today.getDate() - today.getDay();
var firstDayWeek = new Date(today.setDate(first));
var lastDayWeek = new Date(today.setDate(first + 6));
var firstDayMonth = new Date(today.setDate(1));
var lastDayMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0)
lastDayWeek.setHours(23, 59, 59, 0);
lastDayMonth.setHours(23, 59, 59, 0);
today = new Date().setHours(0, 0, 0, 0);

db.getCollection('TEST').aggregate([{
        $match: {
            userId: decode.id
        }
    }, {
        $group: {
            "_id": "",
            "today": {
                $push: {
                    $cond: {
                        if: {
                            $gte: ["$created", new Date(today)]
                        },
                        then: "$$ROOT",
                        else: ''
                    }
                }
            },
            "week": {
                $push: {
                    $cond: [{
                            $and: [{
                                    $gte: ["$created", new Date(firstDayWeek)]
                                },
                                {
                                    $lte: ["$created", new Date(lastDayWeek)]
                                }
                            ]
                        },
                        "$$ROOT",
                        ''
                    ]
                }
            },
            "month": {
                $push: {
                    $cond: [{
                            $and: [{
                                    $gte: ["$created", new Date(firstDayMonth)]
                                },
                                {
                                    $lte: ["$created", new Date(lastDayMonth)]
                                }
                            ]
                        },
                        "$$ROOT",
                        ''
                    ]
                }
            }
        }
    }])
    //If you want to filter in mongo query
    .forEach(function (data) {
        data.today = data.today.filter(e => e != "")
        data.week = data.week.filter(e => e != "")
        print(data);
    })

MongoDB聚合查询:唯一的问题我看到的是$ cond else阻止返回""。您可以在节点js中处理。

{
    "_id": "",
    "today": [{
            "_id": ObjectId("5aaa2605d52a86d42a362479"),
            "created": ISODate("2018-03-15T07:51:33.014Z")
        }
    ],
    "week": [{
            "_id": ObjectId("5aaa2605d52a86d42a362479"),
            "created": ISODate("2018-03-15T07:51:33.014Z")
        },
        {
            "_id": ObjectId("5aaa2606d52a86d42a36247a"),
            "created": ISODate("2018-03-13T07:51:34.702Z")
        }
    ],
    "month": [{
            "_id": ObjectId("5aaa2605d52a86d42a362479"),
            "created": ISODate("2018-03-15T07:51:33.014Z")
        },
        {
            "_id": ObjectId("5aaa2606d52a86d42a36247a"),
            "created": ISODate("2018-03-13T07:51:34.702Z")
        },
        {
            "_id": ObjectId("5aaa262ad52a86d42a36247b"),
            "created": ISODate("2018-03-01T07:52:10.175Z")
        }
    ]
}

<强>输出

UPDATE Orders 
SET menuId = 14259 
WHERE menuId = 14422 
AND userId IN 
(SELECT Id FROM users where Group IN
(SELECT Id FROM groups where eatGroupId = 4))