Registry /
database / loopback-connector-mongodb
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
juggler.DataSource
✓ import { juggler } from '@loopback/repository';
// Usage: new juggler.DataSource(config);
✗ import { DataSource } from 'loopback-connector-mongodb';
In LoopBack 4, `loopback-connector-mongodb` is primarily used via configuration with `@loopback/repository.juggler.DataSource`. The connector itself is loaded by its string name 'mongodb' in the configuration, not directly imported as a class by user code.
Generated DataSource Class
✓ import { DbDataSource } from './datasources/db.datasource';
When using the `lb4 datasource` CLI command, a custom DataSource class (e.g., `DbDataSource`) is generated in your application's `src/datasources` directory. This generated class extends `juggler.DataSource` and is the primary entry point for using the configured MongoDB connection within your LoopBack 4 application.
Full Connector Object (Advanced)
✓ const connector = require('loopback-connector-mongodb');
✗ import * as connector from 'loopback-connector-mongodb';
While less common for direct consumption in modern LB4 applications, you might `require` the package in a CommonJS context for programmatic registration or advanced customization. Direct ESM `import * as` might be empty as the module typically registers itself via side effects rather than exporting a default object for direct use.
This quickstart demonstrates how to define, configure, and bind the `loopback-connector-mongodb` datasource within a minimalistic LoopBack 4 application. It illustrates the use of `juggler.DataSource` with the connector's configuration and includes a basic connection health check by pinging the MongoDB server.
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);
});
Errors
Common errors & fixes
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
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.
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.
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'`.
Audit
Dependencies
@loopback/repositoryrequiredCore LoopBack 4 component for data source management and ORM capabilities. This connector extends its functionality and expects to be used within a `@loopback/repository` context.
mongodbrequiredThe underlying Node.js driver used by the connector to communicate with MongoDB. It is a direct runtime dependency.