在MySQL Loopback Connector上执行原始查询

如何使用strongloop执行原始查询并通过REST API公开结果?

我读过一些关于使用hooksdataSource.connector.query()但我找不到任何工作的例子。

这是一个基本的例子。 如果您有产品模型(/common/models/product.json),请通过添加/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 } } ); }; 

这将创build以下端点示例:GET / Products / byCategory?group = computers

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

  1. 在你的/common/models/model.js暴露一个远程方法
  2. 在远程方法中执行sql查询(通过dataSource.connector.query(sql, cb);