Executing a raw query in MySQL Loopback Connector

How can I execute a raw query and publish the results via the REST API using strongloop?

I read something about using hooks and dataSource.connector.query() , but I can't find any working examples.

+7
mysql loopbackjs strongloop
source share
2 answers

Here is an example. If you have a product model (/common/models/product.json), expand the model by adding the file /common/models/product.js:

 module.exports = function(Product) { Product.byCategory = function (category, cb) { var ds = Product.dataSource; var sql = "SELECT * FROM products WHERE category=?"; ds.connector.query(sql, category, function (err, products) { if (err) console.error(err); cb(err, products); }); }; Product.remoteMethod( 'byCategory', { http: { verb: 'get' }, description: 'Get list of products by category', accepts: { arg: 'category', type: 'string' }, returns: { arg: 'data', type: ['Product'], root: true } } ); }; 

This will create the following endpoint example: GET / Products / byCategory? group = computers

http://docs.strongloop.com/display/public/LB/Executing+native+SQL

+19
source share
  • output the remote method in /common/models/model.js
  • execute sql query in a remote method (via dataSource.connector.query(sql, cb);
+1
source share

All Articles