LoopBack MongoDB Connector

7.0.4 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

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);
});

view raw JSON →