Page Contents

Overview

When you project outgrows built-in Repository methods, you can execute native database commands to implement more complex data queries and manipulations, for example execute a custom SQL query or invoke a MongoDB command.

LoopBack provides two APIs:

  • DataSource-level execute() method
  • Repository-level execute() method

Both methods offer the same set of signatures, the implementation in Repository is just a thin wrapper delegating the task to DataSource.

Example use:

const result = await repository.execute('SELECT * FROM Products');

Examples

MySQL

Use parameterized queries to avoid SQL injection attacks.

const result = await repository.execute('SELECT * FROM Products WHERE id = ?', [
  productId,
]);

PostgreSQL

const result = await repository.execute(
  'SELECT * FROM Products WHERE id = $1',
  [productId],
);

MongoDB

const result = await repository.execute('MyCollection', 'aggregate', [
  {$unwind: '$data'},
  {$out: 'tempData'},
]);

Use parameterized queries whenever possible instead of constructing SQL strings manually.

See API docs for parameter reference, additional information and examples:

Supported connectors

Not all connectors support execution of native database commands. Check your connector’s documentation to learn more. The following connectors are known to support execute method.