You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合管道中Date.now()始终返回相同时间的问题排查

问题根源

列表API的聚合管道是静态常量数组,Date.now()在Node.js首次加载该模块时就会执行并固定值,后续所有请求都会复用这个初始计算的时间,导致时间差值不会随请求更新。而详情API的管道是动态返回数组的函数,每次调用函数时都会重新执行Date.now(),因此能获取当前请求的实时时间。

解决方法

将列表的聚合管道从常量改为函数,确保每次请求时生成新的管道数组,让Date.now()在每次请求时重新计算:

export const GetRecentVideoListPipeLine = () => {
    return [
        {
            '$project': {
                '_id': 1,
                'nickName': 1,
                'thumbNailPath': 1,
                'title': 1,
                'tags': 1,
                'likeCount': 1,
                'uploadedAt': {
                    '$subtract': [
                        Date.now(),
                        '$uploadedAt'
                    ]
                },
            }
        },
        { '$sort': { 'uploadedAt': 1 } }
    ];
};

同时修改调用管道的代码,改为调用函数获取动态生成的数组:

// 原错误调用
await model.aggregate(GetRecentVideoListPipeLine);
// 修改后的正确调用
await model.aggregate(GetRecentVideoListPipeLine());
可选优化方案

如果希望完全依赖数据库端的当前时间(避免客户端与服务器时间差异),可以使用MongoDB 3.6+支持的$$NOW系统变量,该变量会在每次聚合执行时实时获取数据库服务器的当前时间,无需依赖Node.js端的时间计算:

export const GetRecentVideoListPipeLine = [
    {
        '$project': {
            '_id': 1,
            'nickName': 1,
            'thumbNailPath': 1,
            'title': 1,
            'tags': 1,
            'likeCount': 1,
            'uploadedAt': {
                '$subtract': [
                    '$$NOW',
                    '$uploadedAt'
                ]
            },
        }
    },
    { '$sort': { 'uploadedAt': 1 } }
];

内容的提问来源于stack exchange,提问作者Jonathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:39:19