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
相关产品推荐
相关产品推荐

