猫鼬查询循环内部

时间:2019-03-28 13:30:51

标签: node.js mongodb asynchronous mongoose

我正在尝试在for循环中获取查询结果。我的循环就像:

async function f1(date1,date2){

    return await Message.aggregate([
    { $match: {_id: {
        $gt: ObjectId(Math.floor((new Date(date1))/1000).toString(16) + "0000000000000000"),
        $lt: ObjectId(Math.floor((new Date(date2))/1000).toString(16) + "0000000000000000")
        } }},
        ])
    .exec().then(data => {
        return data.length;
    });
}



var now = new Date('2018/06/08');

for (var d = new Date('2018/06/07'); d <= now; d.setDate(d.getDate() + 1)) {

    var date1 = (d.getFullYear())+'/'+(d.getMonth())+'/'+(d.getDate());
    var date2 = (d.getFullYear())+'/'+(d.getMonth())+'/'+(d.getDate()+1);

    f1(date1,date2).then(x => {
        console.log(x);
    });

}


此动态日期循环没有给我任何查询结果。我尝试了异步功能,但我不知道我是否做对了。当我尝试从静态日期获取结果时,例如:

function f2(){
    return Message.aggregate([
    { $match: {_id: {
        $gt: ObjectId(Math.floor((new Date('2018/06/08'))/1000).toString(16) + "0000000000000000"),
        $lt: ObjectId(Math.floor((new Date('2018/06/09'))/1000).toString(16) + "0000000000000000")
        } }},

    ])
    .exec().then(data => {
        return data.length;
    })
}

这给了我正确的结果。我如何在该日期循环内获得结果?

0 个答案:

没有答案