LoopBack MongoDB Connector
The `loopback-connector-mongodb` package provides the official MongoDB connector for the LoopBack 4 framework. It enables LoopBack applications to interact with MongoDB databases by abstracting connection details and CRUD operations. As of version 6.0.0, this connector is exclusively compatible with LoopBack 4 and Juggler 4.x, requiring users of LoopBack 3 to stick to the 5.x branch. The current stable version is 7.0.4. This module adheres to a Module Long Term Support (LTS) policy, ensuring an extended maintenance period for major versions, with version 6.x supported until at least April 2028. Key differentiators include seamless integration with the LoopBack 4 CLI for datasource generation, robust handling of connection configurations, and support for advanced MongoDB features through the underlying Node.js MongoDB driver.
Common errors
-
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
cause The MongoDB server is not running, is inaccessible from the application's host, or is listening on a different port/address than configured.fixVerify that your MongoDB server is running and accessible from where your LoopBack application is executed. Check the configured `host` and `port` in your datasource configuration, firewall rules, and MongoDB's `bindIp` settings. -
Authentication failed.
cause Incorrect username, password, or authentication database (`authSource`) for the MongoDB connection.fixDouble-check your `user`, `password`, and `authSource` configuration properties. Ensure special characters in credentials are URI-encoded using `encodeURIComponent`. Verify the user has necessary permissions on the specified database. -
Error: The connector 'mongodb' is not found. Please make sure the connector module is installed.
cause The `loopback-connector-mongodb` npm package is not installed or not resolvable in the application's `node_modules` directory, or there's a typo in the `connector` property within the datasource configuration.fixRun `npm install loopback-connector-mongodb --save` in your project's root directory. If using a monorepo, verify `package.json` dependencies and workspace configuration. Confirm the `connector` property in your datasource config is exactly `'mongodb'` or `'loopback-connector-mongodb'`.
Warnings
- breaking Version 6.0.0 and above of `loopback-connector-mongodb` are no longer compatible with LoopBack 3 applications. Users must upgrade to LoopBack 4 or remain on the 5.x branch for LoopBack 3 compatibility.
- gotcha Special characters (e.g., `@`, `$`, `/`) in MongoDB usernames or passwords must be URI-encoded when provided in connection strings or configuration properties to avoid parsing errors.
- deprecated Older versions (4.x, 5.x) of `loopback-connector-mongodb` have reached their End-of-Life (EOL) and are no longer actively maintained or supported. Continuing to use them may expose applications to security vulnerabilities or compatibility issues.
- gotcha The connector specifies Node.js runtime compatibility. As of version 7.x, it requires Node.js version 20, 22, or 24. Using incompatible Node.js versions can lead to installation failures or runtime errors.
Install
-
npm install loopback-connector-mongodb -
yarn add loopback-connector-mongodb -
pnpm add loopback-connector-mongodb
Imports
- juggler.DataSource
import { DataSource } from 'loopback-connector-mongodb';import { juggler } from '@loopback/repository'; // Usage: new juggler.DataSource(config); - Generated DataSource Class
import { DbDataSource } from './datasources/db.datasource'; - Full Connector Object (Advanced)
import * as connector from 'loopback-connector-mongodb';
const connector = require('loopback-connector-mongodb');
Quickstart
import { juggler } from '@loopback/repository';
import { Application, Binding, Component, CoreBindings, createApplication } from '@loopback/core';
// 1. Define your MongoDB data source configuration
const config = {
name: 'mongoDs',
connector: 'mongodb',
host: 'localhost',
port: 27017,
user: process.env.MONGO_USER ?? '', // Use environment variables for credentials
password: process.env.MONGO_PASSWORD ?? '',
database: 'testdb',
url: process.env.MONGO_URL ?? '', // This URL will override host, port, user, password, database if provided
};
// 2. Create a custom DataSource class extending juggler.DataSource.
// This mirrors the structure generated by 'lb4 datasource'.
class MyMongoDataSource extends juggler.DataSource {
static dataSourceName = 'mongoDs';
static readonly defaultConfig = config;
constructor(dsConfig: object = config) {
super(dsConfig);
}
}
// 3. Example of binding and using the datasource in a minimalistic LoopBack application.
async function main() {
const app = new Application();
// Bind the datasource to the application context. This makes it available via dependency injection.
app.dataSource(new MyMongoDataSource());
// Retrieve the datasource from the application context to interact with it.
const myDs = await app.get<juggler.DataSource>('datasources.mongoDs');
console.log('MongoDB DataSource initialized with name:', myDs.settings.name);
// Example: Perform a simple connection health check (conceptual, actual method depends on connector).
try {
// Connectors expose their underlying client. For MongoDB, we can ping the database.
const client = await (myDs.connector as any).client;
const db = client.db(config.database);
const result = await db.admin().ping();
console.log('MongoDB ping successful:', result);
} catch (err) {
console.error('Failed to connect or ping MongoDB:', err);
process.exit(1);
}
// In a real application, you'd define models and repositories here to use the datasource.
// For this example, we just start and stop the app to show initialization.
await app.start();
console.log('Application started. DataSource bound and verified.');
await app.stop();
console.log('Application stopped.');
}
main().catch(err => {
console.error('Error during application lifecycle:', err);
process.exit(1);
});