LoopBack远程方法和对模型数据的访问

我一直在这个工作了几个小时,我完全失去了,因为环回文档没有帮助。

我正在尝试将应用程序逻辑写入模型。 这里的文档就在这里 。 不幸的是,除了将外部值传递给远程方法并再次返回外,该示例没有演示任何有用的内容。 我想了解如何在这个上下文中运行查询并访问模型数据,但是我已经search了几个小时,甚至找不到这些简单任务的文档。 也许我只是看错了地方。 谁能帮忙?

通常情况下,您可以通过所有模型获取的内置方法完成您想要执行的大多数操作,例如查询和访问模型数据(CRUD操作) 请参阅http://docs.strongloop.com/display/LB/Working+with+data 。 为这些定义远程方法(自定义REST端点)将是多余的。

如果需要,可以在远程方法代码中访问标准模型CRUD节点API (例如,myModel.create(),myModel.find(),myModel.updateAll())。

您也可以在https://github.com/strongloop/loopback-example-app-logic中find更多相关示例

以下是使用入门应用程序https://github.com/strongloop/loopback-getting-started应用程序的示例。 它定义了一个远程方法,它接受一个数字arg,并将该ID的咖啡店名称打印到控制台:

这段代码是common / models / coffeeshop.js:

module.exports = function(CoffeeShop) { ... // Return Coffee Shop name given an ID. CoffeeShop.getName = function(shopId, cb) { CoffeeShop.findById( shopId, function (err, instance) { response = "Name of coffee shop is " + instance.name; cb(null, response); console.log(response); }); } ... CoffeeShop.remoteMethod ( 'getName', { http: {path: '/getname', verb: 'get'}, accepts: {arg: 'id', type: 'number', http: { source: 'query' } }, returns: {arg: 'name', type: 'string'} } ); }; 

我终于发现我的问题。 对象属性必须在调用CRUD操作的函数的callback中加载。 以下语法适用于我:

 module.exports = function (TestModel) { TestModel.testRemoteMethod = function (id, name, cb) { TestModel.findOne({where: {id: id}}, function(err, modelInstance) { //modelInstance has properties here and can be returned to //the API call using the callback, for example: cb(null, {"name": modelInstance.name}); } } TestModel.remoteMethod('testRemoteMethod', //..rest of config