RangeError:超过mongoose的最大调用堆栈大小

我正在尝试使用时间段进行聚合。 然后,我想返回一个数组,每天都有值(没有find文档时为0)。 aggeagate函数令人惊叹,但是当我replacecallback(以前的console.log)是这样的:

Star.aggregate([{ $match: { "mod": new mongoose.Types.ObjectId("53765a122c0cda28199df3f4"), "time_bucket.month": new TimeBucket().month } }, { $group: { _id: "$time_bucket.day", stars: { "$sum": 1 } } }, { $sort: { '_id': 1 } }], function (err, mods) { console.log(err, mods); mods = mods.map(function (model) { return model.toObject ? model.toObject() : model }); var i, time, docs = []; var hasGap = function (a, b) { a = a.replace(/-/g, ''); b = b.replace(/-/g, ''); return a - b !== 1 } var process = function (i, mods, docs) { if (hasGap(mods[i]._id, mods[i + 1]._id)) { docs.push(0); return process(i, mods, docs) } docs.push(mods[i].stars); return process(i + 1, mods, docs) }; process(0, mods, docs); console.log(docs); }); 

我得到:

 C:\Users\Me\Nodejs\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\base.js:245 throw message; ^ RangeError: Maximum call stack size exceeded 

你的process函数是recursion的,并且没有path通过不再调用process来中断recursion。 一个经典的无限recursion堆栈溢出。

解决方法是更改process函数,以便检查结果文档的mods数组的末尾,然后在那一刻返回,而不是再次调用自己。

所以这样的检查:

 if (i >= mods.length) return;