@agendajs/mongo-backend

中文文档
4.0.4发布于 2026/10/31MITTypeScriptES Module构建来源已验证近 30 天下载 10万

MongoDB backend for Agenda job scheduler

原始使用文档
文档目录16 节
  1. Installation
  2. Usage
  3. Configuration Options
  4. Full Example with Options
  5. Real-Time Notifications
  6. Option 1: MongoDB Change Streams (Native)
  7. Option 2: In-Memory (Single Process)
  8. Option 3: Redis Pub/Sub (Multi-Process)
  9. Database Index
  10. Additional Indexes
  11. Job Logging
  12. Automatic Usage
  13. Standalone Usage
  14. Querying Logs
  15. Related Packages
  16. License

@agendajs/mongo-backend

MongoDB backend for Agenda job scheduler.

Installation

npm install agenda @agendajs/mongo-backend
# or
pnpm add agenda @agendajs/mongo-backend
# or
yarn add agenda @agendajs/mongo-backend

Requirements:

  • Node.js 18+
  • MongoDB 4+

Usage

import { Agenda } from 'agenda';
import { MongoBackend } from '@agendajs/mongo-backend';

// Via connection string
const agenda = new Agenda({
  backend: new MongoBackend({
    address: 'mongodb://localhost/agenda'
  })
});

// Or via existing MongoDB connection
import { MongoClient } from 'mongodb';

const client = await MongoClient.connect('mongodb://localhost');
const db = client.db('agenda');

const agenda = new Agenda({
  backend: new MongoBackend({ mongo: db })
});

// Define jobs
agenda.define('send-email', async (job) => {
  const { to, subject } = job.attrs.data;
  await sendEmail(to, subject);
});

// Start processing
await agenda.start();

// Schedule jobs
await agenda.every('1 hour', 'send-email', { to: '[email protected]', subject: 'Hello' });

Configuration Options

interface IMongoBackendConfig {
  /** MongoDB connection string */
  address?: string;

  /** Existing MongoDB database instance */
  mongo?: Db;

  /** Collection name for jobs (default: 'agendaJobs') */
  collection?: string;

  /** MongoDB client options */
  options?: MongoClientOptions;

  /** Name to identify this Agenda instance (stored as lastModifiedBy) */
  name?: string;

  /** Whether to create indexes on connect (default: true) */
  ensureIndex?: boolean;

  /** Sort order for job queries */
  sort?: { [key: string]: SortDirection };
}

Full Example with Options

const agenda = new Agenda({
  backend: new MongoBackend({
    address: 'mongodb://localhost/agenda',
    collection: 'jobs',           // Custom collection name
    sort: { nextRunAt: 'asc', priority: 'desc' }
  }),
  processEvery: '30 seconds',     // Job polling interval
  maxConcurrency: 20,             // Max concurrent jobs
  defaultConcurrency: 5           // Default per job type
});

Real-Time Notifications

MongoBackend provides storage only and uses polling to check for new jobs. For real-time job processing across distributed systems, you have several options:

Option 1: MongoDB Change Streams (Native)

If your MongoDB deployment is a replica set (even a single-node replica set works), you can use MongoChangeStreamNotificationChannel for native real-time notifications without any external dependencies:

import { Agenda } from 'agenda';
import { MongoBackend, MongoChangeStreamNotificationChannel } from '@agendajs/mongo-backend';

const agenda = new Agenda({
  backend: new MongoBackend({ mongo: db }),
  notificationChannel: new MongoChangeStreamNotificationChannel({ db })
});

// Jobs are processed immediately when created (no polling delay)
await agenda.start();
await agenda.now('myJob'); // Triggers instant processing

Requirements:

  • MongoDB replica set (single-node replica sets work fine)
  • WiredTiger storage engine (default since MongoDB 3.2)

Configuration options:

const channel = new MongoChangeStreamNotificationChannel({
  db: mongoDb,                    // Required: MongoDB database instance
  collection: 'agendaJobs',       // Optional: collection name (default: 'agendaJobs')
  resumeToken: savedToken,        // Optional: resume from specific point
  fullDocument: true              // Optional: include full document on updates (default: true)
});

Option 2: In-Memory (Single Process)

import { Agenda, InMemoryNotificationChannel } from 'agenda';
import { MongoBackend } from '@agendajs/mongo-backend';

// For single-process apps (testing/development)
const agenda = new Agenda({
  backend: new MongoBackend({ mongo: db }),
  notificationChannel: new InMemoryNotificationChannel()
});

Option 3: Redis Pub/Sub (Multi-Process)

import { Agenda } from 'agenda';
import { MongoBackend } from '@agendajs/mongo-backend';
import { RedisBackend } from '@agendajs/redis-backend';

// For production: use Redis for notifications
const redisBackend = new RedisBackend({ connectionString: 'redis://localhost:6379' });
const agenda = new Agenda({
  backend: new MongoBackend({ mongo: db }),
  notificationChannel: redisBackend.notificationChannel
});

Database Index

By default, MongoBackend automatically creates the findAndLockNextJobIndex index on connect for optimal job query performance. The index includes:

{
  "name": 1,
  "nextRunAt": 1,
  "priority": -1,
  "lockedAt": 1,
  "disabled": 1
}

To disable automatic index creation (e.g., if you manage indexes separately):

const backend = new MongoBackend({
  mongo: db,
  ensureIndex: false  // Skip automatic index creation
});

Additional Indexes

If you use Agendash, add this index for better dashboard performance:

db.agendaJobs.createIndex({
  "nextRunAt": -1,
  "lastRunAt": -1,
  "lastFinishedAt": -1
}, { name: "agendash" })

If you have job definitions with thousands of instances, this index can improve lock queries:

db.agendaJobs.createIndex({
  "name": 1,
  "disabled": 1,
  "lockedAt": 1
}, { name: "findAndLockDeadJobs" })

Job Logging

MongoBackend includes a built-in MongoJobLogger that stores structured job lifecycle events in a dedicated MongoDB collection (agenda_logs by default). The logger is lightweight and only creates its collection on first use.

Automatic Usage

When you enable logging in Agenda, the backend's built-in logger is used automatically:

const agenda = new Agenda({
  backend: new MongoBackend({ mongo: db }),
  logging: true  // Uses MongoJobLogger automatically
});

Standalone Usage

You can also use MongoJobLogger independently — for example, to log to MongoDB while using a different backend for storage:

import { MongoJobLogger } from '@agendajs/mongo-backend';

const logger = new MongoJobLogger({
  mongo: db,                        // Required: MongoDB database instance
  logCollection: 'agenda_logs'      // Optional: collection name (default: 'agenda_logs')
});

// Use with any backend
import { RedisBackend } from '@agendajs/redis-backend';
const agenda = new Agenda({
  backend: new RedisBackend({ connectionString: 'redis://...' }),
  logging: logger
});

Querying Logs

const { entries, total } = await agenda.getLogs({
  jobName: 'send-email',
  level: 'error',
  limit: 50,
  sort: 'desc'
});

// Clear old logs
await agenda.clearLogs({ to: new Date(Date.now() - 30 * 86400000) });

See the Agenda README for full logging documentation.

License

MIT

版本与发布记录

@agendajs/mongo-backend 共发布 12 个版本,首次发布于 2026/01/26;过去 12 个月发布了 12 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.0.4latest2026/10/317 天前
4.0.32026/07/213 个月前
4.0.22026/05/095 个月前
4.0.12026/04/027 个月前
4.0.02026/02/268 个月前
3.2.02026/02/168 个月前

其他发布通道:alpha → 1.0.0-alpha.0。

关于 @agendajs/mongo-backend 的常见问题

@agendajs/mongo-backend 是什么?

MongoDB backend for Agenda job scheduler

如何安装 @agendajs/mongo-backend?

在项目目录运行 npm install @agendajs/mongo-backend,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:agenda(6.2.7)、mongodb(^6.0.0 || ^7.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@agendajs/mongo-backend 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@agendajs/mongo-backend 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@agendajs/mongo-backend 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@agendajs/mongo-backend 可以商用吗?

@agendajs/mongo-backend 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@agendajs/mongo-backend 的下载量有多少?

根据 npm 官方下载统计,@agendajs/mongo-backend 在 2026/10/05 – 2026/11/03 这 30 天内被下载 99,535 次,日均约 3,318 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@agendajs/mongo-backend 还在维护吗?

最新版本 4.0.4 发布于 2026/10/31(7 天前);至今共发布 12 个版本,其中过去 12 个月发布了 12 个;首次发布于 2026/01/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。