在项目中使用agenda执行一些周期性任务,初始化项目集成agendash时候遇到一个问题
E:\git\agenda-service\node_modules\agendash\lib\controllers\agendash.js:9
const collection = agenda._collection.collection || agenda._collection;
^
TypeError: Cannot read properties of undefined (reading 'collection')
at Agenda.<anonymous> (E:\git\agenda-service\node_modules\agendash\lib\controllers\agendash.js:9:43)
at Agenda.emit (node:events:402:35)
at Agenda.emit (node:domain:475:12)
at JobDbRepository.connect (E:\git\agenda-service\node_modules\@hokify\agenda\src\JobDbRepository.ts:209:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
该异常显示没有_collection,使用的版本如下package.json
"devDependencies": {
"@types/express": "^4.17.21",
"@types/node": "^22.5.4",
"dotenv-cli": "^7.4.2",
"ts-node": "^10.9.2",
"typescript": "^5.5.4"
},
"dependencies": {
"@hokify/agenda": "^6.3.0",
"agendash": "^4.0.0",
"dotenv": "^16.4.5",
"express": "^4.19.2"
}
可以明确的是agendash 4.0.0的版本是没有解决这个问题的,估计是agenda的数据结构发生了变动,但是agendash这边还没有更新导致的,断点进去看了报错的地方,以下是其中一处在agenda.js中
agenda.on("ready", () => {
const collection = agenda._collection.collection || agenda._collection;
collection.createIndexes(
[
{ key: { nextRunAt: -1, lastRunAt: -1, lastFinishedAt: -1 } },
{ key: { name: 1, nextRunAt: -1, lastRunAt: -1, lastFinishedAt: -1 } },
],
(error) => {
if (error) {
// Ignoring for now
}
}
);
断点可以看到与collection类似的属性实际上为db.collection 全局批量替换,可以修复该异常
另外agendash中有一个判定当前连接使用的mongodb的引用到了_mdb,该字段同样没有,确保自己的mongo version大于3.6然后直接注释掉这部分代码
agenda.on("ready", () => {
const collection = agenda.db.collection || agenda.db;
collection.createIndexes(
[
{ key: { nextRunAt: -1, lastRunAt: -1, lastFinishedAt: -1 } },
{ key: { name: 1, nextRunAt: -1, lastRunAt: -1, lastFinishedAt: -1 } },
],
(error) => {
if (error) {
// Ignoring for now
}
}
);
// Mongoose internals changed at some point. This will fix crash for older versions.
// const mdb = agenda._mdb.admin ? agenda._mdb : agenda._mdb.db;
// mdb.admin().serverInfo((error, serverInfo) => {
// if (error) {
// throw error;
// }
// if (!semver.satisfies(semver.coerce(serverInfo.version), ">=3.6.0")) {
// throw new Error("MongoDB version not supported");
// }
// });
});