Registry / database / loopback-connector-mongodb

loopback-connector-mongodb

JSON →
library7.0.4jsnpmunverified

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.

npm install loopback-connector-mongodb
INSTALL
IMPORT
SIG · LOOPBACK-CONNECTOR
L
loopback-connector-mongodb
databasejavascriptv7.0.4
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
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
musl
node 18226 runs
build_error
glibc
node 18226 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); });
Debug
Known issues
breakingVersion 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.
fix
For LoopBack 3 projects, use `npm install loopback-connector-mongodb@5.x --save`. For LoopBack 4 projects, ensure your application and other LoopBack dependencies are updated to their latest compatible versions.
affects: >=6.0.0
gotchaSpecial characters (e.g., `@`, `$`, `/`) in MongoDB usernames or passwords must be URI-encoded when provided in connection strings or configuration properties to avoid parsing errors.
fix
Use `encodeURIComponent()` on the username and password before constructing the connection URL or assigning to `user`/`password` properties. For example, `pa$$wd` would become `pa%24%24wd`.
affects: >=4.0.0
deprecatedOlder 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.
fix
Upgrade to the latest stable version (currently 7.x) of `loopback-connector-mongodb` and ensure your LoopBack 4 application is also on a compatible recent version. Review the Module LTS table for specific EOL dates and plan your upgrade accordingly.
affects: <6.0.0
gotchaThe 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.
fix
Ensure your project's `engines.node` in `package.json` is configured correctly, and use a Node.js version manager (e.g., `nvm` or `volta`) to switch to a supported runtime before installation and execution.
affects: >=7.0.0
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.
fix
Verify 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.
fix
Double-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.
fix
Run `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'`.
Upgrade
Version history
7.0.4latest on npm
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.
Agent activity
14 hits · last 30 days
node
14
Resources