Registry / database / mongo-dlock

mongo-dlock

JSON →
library2.0.4jsnpmunverified

Distributed lock implementation based on MongoDB for Node.js, version 2.0.4. It supports one-shot lock attempts and automatic retry via polling, lock refresh (including auto-refresh), and data payloads attached to locks. Uses MongoDB TTL indexes to clean up stray locks. The 2.0.0 major release removed pubsub-based event propagation via a capped collection and EventEmitter, simplifying the internals to rely solely on polling. Compared to alternatives like Redis-based locks, mongo-dlock leverages existing MongoDB infrastructure without additional services. It defaults to a 15-second lock expiration and a 5-second polling interval.

npm install mongo-dlock
INSTALL
IMPORT
SIG · MONGO-DLOCK
M
mongo-dlock
databasejavascriptv2.0.4
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.

MDL
import MDL from 'mongo-dlock'
const MDL = require('mongo-dlock')
Default import using ESM syntax. CommonJS require also works due to package compatibility.
MongoDLock
import MDL from 'mongo-dlock'; const mongoDLock = await new Promise((resolve, reject) => MDL(opts, (err, v) => err ? reject(err) : resolve(v)))
const MongoDLock = require('mongo-dlock').MongoDLock
MongoDLock is not directly exported; it is the factory returned to the callback of MDL.
DLock
import MDL from 'mongo-dlock'; const mongoDLock = await ...; const dlock = mongoDLock.dlock('task')
import { DLock } from 'mongo-dlock'
DLock instances are created via MongoDLock.dlock(), not imported directly.

Demonstrates initialization, acquiring a lock with automatic retry, and releasing with proper cleanup.

import MDL from 'mongo-dlock'; const opts = { url: process.env.MONGO_URL ?? 'mongodb://localhost:27017', db: 'dlocks', coll: 'dlocks', grace: 60, exp_delta: 15000, autorefresh: true, wait_lock_period: 5000 }; MDL(opts, (err, Locks) => { if (err) { console.error('Failed to initialize locks:', err); return; } const l1 = Locks.dlock('some-task'); l1.wait_lock(err => { if (err) { console.error('Failed to acquire lock:', err); return; } console.log('Lock acquired!'); // Perform the task... setTimeout(() => { l1.unlock(err => { if (err) console.error('Failed to unlock:', err); Locks.close(err => { if (err) console.error('Failed to close:', err); console.log('Done'); }); }); }, 2000); }); });
Debug
Known issues
breakingv2.0.0 removed pubsub-based event propagation (capped collection + EventEmitter). Wait_lock now relies solely on polling.
fix
Update code to not depend on pubsub events. Polling is now the only mechanism.
affects: >=2.0.0
gotchaAutorefresh sets an internal interval; locks must be manually unlocked to stop the interval, or they will keep refreshing until the application shuts down.
fix
Ensure unlock() is called to stop autorefresh and release the lock.
affects: *
gotchaThe 'upd' option for extra MongoDB updates must follow the updateOne() syntax. Using an object instead of a function works only if the update does not need to change over time.
fix
Use a function returning the update object if dynamic updates are needed (e.g., including a timestamp on each refresh).
affects: *
deprecatedThe callback-based API is the primary interface. Promisification is left to the user.
fix
Wrap calls with util.promisify or use async/await with a promise adapter.
affects: *
Errors
Common errors & fixes
Error: connect ECONNREFUSED ::1:27017
MongoDB not running on the default localhost:27017 or connection URL missing.
fix
Ensure MongoDB is running and provide the correct URL via opts.url or environment variable MONGO_URL.
MongoError: E11000 duplicate key error collection: dlocks.dlocks index: id_1 dup key: { id: "some-task" }
Race condition where two lock acquisition attempts insert the same lock ID. This is expected and handled internally by wait_lock retrying.
fix
No action needed; wait_lock retries automatically. If using try_lock, handle the error gracefully.
TypeError: MDL is not a function
CommonJS require returns the default export incorrectly, or ESM import used without default export.
fix
Use `const MDL = require('mongo-dlock')` for CommonJS, or `import MDL from 'mongo-dlock'` for ESM.
Cannot read properties of undefined (reading 'dlock')
MDL callback called with error that was not handled, and the Locks parameter is undefined.
fix
Check the error parameter in the MDL callback before using Locks.
Upgrade
Version history
2.0.4latest on npm
Audit
Dependencies
mongodbrequiredProvides the MongoDB driver for database operations.
Agent activity
3 hits · last 30 days
node
2
Amazon
1
Resources
mongo-dlock — npm install mongo-dlock · libregistry