{"id":15136,"library":"loopback-connector-mongodb","title":"LoopBack MongoDB Connector","description":"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.","status":"active","version":"7.0.4","language":"javascript","source_language":"en","source_url":"git://github.com/loopbackio/loopback-connector-mongodb","tags":["javascript","connector","datasource","loopback","mongodb"],"install":[{"cmd":"npm install loopback-connector-mongodb","lang":"bash","label":"npm"},{"cmd":"yarn add loopback-connector-mongodb","lang":"bash","label":"yarn"},{"cmd":"pnpm add loopback-connector-mongodb","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core 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.","package":"@loopback/repository","optional":false},{"reason":"The underlying Node.js driver used by the connector to communicate with MongoDB. It is a direct runtime dependency.","package":"mongodb","optional":false}],"imports":[{"note":"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.","wrong":"import { DataSource } from 'loopback-connector-mongodb';","symbol":"juggler.DataSource","correct":"import { juggler } from '@loopback/repository';\n// Usage: new juggler.DataSource(config);"},{"note":"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.","symbol":"Generated DataSource Class","correct":"import { DbDataSource } from './datasources/db.datasource';"},{"note":"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.","wrong":"import * as connector from 'loopback-connector-mongodb';","symbol":"Full Connector Object (Advanced)","correct":"const connector = require('loopback-connector-mongodb');"}],"quickstart":{"code":"import { juggler } from '@loopback/repository';\nimport { Application, Binding, Component, CoreBindings, createApplication } from '@loopback/core';\n\n// 1. Define your MongoDB data source configuration\nconst config = {\n  name: 'mongoDs',\n  connector: 'mongodb',\n  host: 'localhost',\n  port: 27017,\n  user: process.env.MONGO_USER ?? '', // Use environment variables for credentials\n  password: process.env.MONGO_PASSWORD ?? '',\n  database: 'testdb',\n  url: process.env.MONGO_URL ?? '', // This URL will override host, port, user, password, database if provided\n};\n\n// 2. Create a custom DataSource class extending juggler.DataSource.\n//    This mirrors the structure generated by 'lb4 datasource'.\nclass MyMongoDataSource extends juggler.DataSource {\n  static dataSourceName = 'mongoDs';\n  static readonly defaultConfig = config;\n\n  constructor(dsConfig: object = config) {\n    super(dsConfig);\n  }\n}\n\n// 3. Example of binding and using the datasource in a minimalistic LoopBack application.\nasync function main() {\n  const app = new Application();\n\n  // Bind the datasource to the application context. This makes it available via dependency injection.\n  app.dataSource(new MyMongoDataSource());\n\n  // Retrieve the datasource from the application context to interact with it.\n  const myDs = await app.get<juggler.DataSource>('datasources.mongoDs');\n  console.log('MongoDB DataSource initialized with name:', myDs.settings.name);\n\n  // Example: Perform a simple connection health check (conceptual, actual method depends on connector).\n  try {\n    // Connectors expose their underlying client. For MongoDB, we can ping the database.\n    const client = await (myDs.connector as any).client;\n    const db = client.db(config.database);\n    const result = await db.admin().ping();\n    console.log('MongoDB ping successful:', result);\n  } catch (err) {\n    console.error('Failed to connect or ping MongoDB:', err);\n    process.exit(1);\n  }\n\n  // In a real application, you'd define models and repositories here to use the datasource.\n  \n  // For this example, we just start and stop the app to show initialization.\n  await app.start();\n  console.log('Application started. DataSource bound and verified.');\n  await app.stop();\n  console.log('Application stopped.');\n}\n\nmain().catch(err => {\n  console.error('Error during application lifecycle:', err);\n  process.exit(1);\n});\n","lang":"typescript","description":"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."},"warnings":[{"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.","message":"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.","severity":"breaking","affected_versions":">=6.0.0"},{"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`.","message":"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.","severity":"gotcha","affected_versions":">=4.0.0"},{"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.","message":"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.","severity":"deprecated","affected_versions":"<6.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=7.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"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.","cause":"The MongoDB server is not running, is inaccessible from the application's host, or is listening on a different port/address than configured.","error":"MongooseServerSelectionError: connect ECONNREFUSED ::1:27017"},{"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.","cause":"Incorrect username, password, or authentication database (`authSource`) for the MongoDB connection.","error":"Authentication failed."},{"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'`.","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.","error":"Error: The connector 'mongodb' is not found. Please make sure the connector module is installed."}],"ecosystem":"npm"}