Back to Loopback Next

Creating DataSources at Runtime

docs/site/Creating-datasource-runtime.md

4.0.0-alpha.1837 B
Original Source

A datasource can be created at runtime by creating an instance of juggler.DataSource. It requires a name for the datasource, the connector, and the connection details.

ts
import {juggler} from '@loopback/repository';
const dsName = 'bookstore-ds';
const bookDs = new juggler.DataSource({
  name: dsName,
  connector: require('loopback-connector-mongodb'),
  url: 'mongodb://sysop:moon@localhost',
});
await bookDs.connect();
app.dataSource(bookDs, dsName);

For details about datasource options, refer to the DataSource documentation.

Attach the newly created datasource to the app by calling app.dataSource().

{% include note.html content=" The app.datasource() method is available only on application classes with RepositoryMixin applied. " %}