Monk Middleware Wait for Connection

raw JSON →
0.2.0 verified Sat Apr 25 auth: no javascript

A thin middleware for the Monk MongoDB driver that defers all database operations until the underlying MongoDB connection is fully established. Version 0.2.0 is stable, released infrequently, and is part of the Monk middleware ecosystem. It prevents race conditions by queueing queries before the connection is ready. Unlike manual connection checks, this transparently applies to all collections registered in Monk.

error TypeError: db.addMiddleware is not a function
cause Attempting to call addMiddleware on a Monk instance that does not support it (e.g., older Monk version or incorrect import).
fix
Ensure you are using Monk version 5.x or later (where middleware was introduced). Upgrade monk to >=5.0.0.
error Error: Cannot find module 'monk-middleware-wait-for-connection'
cause Package not installed or not in node_modules.
fix
Run 'npm install monk-middleware-wait-for-connection' to add the package.
gotcha Middleware must be added before any operations are performed on collections, otherwise those operations may execute before the connection is ready.
fix Ensure db.addMiddleware(waitForConnection) is called immediately after creating the Monk instance, before any collection.get() or queries.
gotcha This middleware only works with Monk's middleware system. If you bypass Monk and access the native MongoDB driver directly, the middleware will not be applied.
fix Always use Monk's API (db.get(), collection.find(), etc.) to benefit from the middleware.
npm install monk-middleware-wait-for-connection
yarn add monk-middleware-wait-for-connection
pnpm add monk-middleware-wait-for-connection

Shows how to apply the wait-for-connection middleware to a Monk database instance, ensuring that subsequent collection operations are queued until the MongoDB connection is established.

import monk from 'monk';
import waitForConnection from 'monk-middleware-wait-for-connection';

const db = monk('localhost/mydb');

db.addMiddleware(waitForConnection);

const collection = db.get('mycollection');

// This operation will wait until the connection is ready
collection.insert({ name: 'test' })
  .then(doc => console.log('Inserted:', doc))
  .catch(err => console.error('Error:', err));