Registry / messaging / mongomq2

mongomq2

JSON →
library1.4.1jsnpmunverified

A lightweight Node.js library that turns MongoDB collections into general-purpose message queues or event logs without additional infrastructure. Version 1.4.1 is stable; released regularly with breaking changes documented. Key differentiators: supports both at-most-once (subscribe) and at-least-once (consume) delivery, configurable retries/visibility/delays, batch publishing, and leverages MongoDB features like indexes, capped collections, transactions, and sharding. No external broker required; designed for event-driven architectures on existing MongoDB deployments. Peer dependency mongodb >=4. Requires Node >=18. Ships TypeScript types.

npm install mongomq2
INSTALL
IMPORT
SIG · MONGOMQ2
M
mongomq2
messagingjavascriptv1.4.1
harness data pending
Install & Compatibility
Where this runs

No compatibility data collected yet for this library.

Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

MessageQueue
import { MessageQueue } from 'mongomq2'
import MessageQueue from 'mongomq2'
Named export from ESM package. Default import is not available.
MessageQueue
const { MessageQueue } = require('mongomq2')
const MessageQueue = require('mongomq2')
CJS destructured require works. Incorrect assignment results in an object with MessageQueue property.
types
import type { MessageQueueOptions, ConsumeOptions, SubscribeOptions } from 'mongomq2'
import { MessageQueueOptions } from 'mongomq2'
Use import type for type-only imports (TypeScript 3.8+). Importing as values is unnecessary and can cause issues in certain bundlers.

Initializes a MongoDB client, creates a MessageQueue from a collection, publishes a message, and consumes messages in a consumer group.

import { MongoClient } from 'mongodb'; import { MessageQueue } from 'mongomq2'; const client = new MongoClient(process.env.MONGO_URI ?? 'mongodb://localhost:27017'); await client.connect(); const collection = client.db('test').collection('messages'); const queue = new MessageQueue(collection, { pollIntervalMs: 1000 }); // Consume messages queue.consume<{ type: string; payload: string }>( async (msg) => { console.log(`Received: ${msg.payload}`); }, { group: 'worker', filter: { type: 'event' } } ); // Publish a message await queue.publish({ type: 'event', payload: 'Hello!' }); // Keep process alive await new Promise(() => {});
Debug
Known issues
breakingv1.x changed the API completely from v0.x. The MessageQueue class replaced createQueue() and other functions.
fix
Upgrade from v0.x? Rewrite usage using the new MessageQueue class. See migration guide in the GitHub repo.
affects: >=1.0.0
breakingconsume() callback must be async and return void. Throwing inside the callback will mark the message as errored and retry according to config. Not returning a promise will result in undefined behavior.
fix
Ensure the consumer callback is async and handles errors internally or throws intentionally to trigger retry.
affects: *
deprecatedThe static method MessageQueue.create() is deprecated since v1.1. Use constructor directly.
fix
Replace MessageQueue.create(collection) with new MessageQueue(collection).
affects: >=1.1.0
gotchaIf the MongoDB collection is a capped collection, insertions will fail once the collection is full. publish() will throw an error due to capped collection overflow.
fix
Use a regular (uncapped) collection for message queues that need to retain history or use a TTL index to auto-expire messages.
affects: *
gotchaMessages published during a transaction may be invisible to consumers until the transaction commits. Subsequent retries could cause duplicate processing if the consumer is not idempotent.
fix
Ensure consumer logic is idempotent or avoid using transactions with publish().
affects: *
gotchaThe subscribe() callback runs in a fire-and-forget manner. If the callback throws, that error is caught and logged, but the message is not acknowledged nor retried. This can lead to silent message loss.
fix
Use consume() with a proper group if you need reliability. Use subscribe() only for non-critical notifications.
affects: *
Errors
Common errors & fixes
Cannot find module 'mongomq2' or its corresponding type declarations
Package is ESM-only. Using require() or importing from a CJS project without proper configuration.
fix
Update package.json to include "type": "module" or use dynamic import() in CJS: const { MessageQueue } = await import('mongomq2');
TypeError: messageCollection.collection is not a function
Passing a Db object instead of a Collection object to the MessageQueue constructor.
fix
Use client.db().collection('name') to get a Collection instance.
MongoError: E11000 duplicate key error collection
Two messages with the same _id (or unique index conflict) are being published. This happens if the user sets _id manually or if there is a unique index on the collection.
fix
Remove the _id field from published objects to let MongoDB auto-generate them, or use a unique index for message deduplication and catch the error.
TimeoutError: Message consumption timed out after 30000ms
Consumer callback took longer than the visibility timeout (default 30s) without acknowledging the message. The queue will reprocess the message.
fix
Reduce the callback execution time or increase the visibility timeout in ConsumeOptions (e.g., { visibilityTimeoutMs: 60000 }).
Upgrade
Version history
1.4.1latest on npm
Audit
Dependencies
mongodbrequiredPeer dependency; MessageQueue constructor expects a MongoDB Collection instance from the mongodb driver.
Agent activity
3 hits · last 30 days
node
2
OpenAI (training)
1
Resources
mongomq2 — npm install mongomq2 · libregistry