回环REST findById不能正常工作
我想通过REST API使用findById
函数。
我把“ID”定义为所有由数字构成的string。
我试图通过IDfind,系统似乎认出它的号码。
当ID是一个大于“9007199254740992”的整数时,我不能使用它。
我想使用ID就像string。
请告诉我如何解决这个问题。
谢谢,
– 跟进 –
我的程序如下。
Model – sample-model.json
{ "name": "SampleModel", "base": "PersistedModel", "idInjection": true, "properties": { "id": { "type": "string", "id": "true", "required": true, "doc": "MODEL ID" }, "prop1": { "type": "string", "required": true } }, "validations": [], "relations": {}, "acls": [], "methods": [] }
当我通过REST API访问findById
函数时,我总是得到以下debugging消息。
strong-remoting:shared-method - findById - invoke with +11ms [ 9007199254740992, undefined, [Function: callback] ] strong-remoting:shared-method - findById - result null +25ms strong-remoting:rest-adapter Invoking rest.after for SampleModel.findById +6ms express:router restRemoteMethodNotFound : /api/SampleModels/9007199254740993 +143ms express:router restUrlNotFound : /api/SampleModels/9007199254740993 +8ms express:router restErrorHandler : /api/SampleModels/9007199254740993 +2ms strong-remoting:rest-adapter Error in GET /SampleModels/9007199254740993: Error: Unknown "SampleModel" id "9007199254740993".
我自己解决了我的问题。
我们可以使用“accepted”选项来定义远程方法接受的参数。
内置的findById
函数在PersistedModel中定义如下:
accepts: [ { arg: 'id', type: 'any', description: 'Model id', required: true, http: {source: 'path'}}, { arg: 'filter', type: 'object', description: 'Filter defining fields and include'} ],
当type
被定义时, id
由HttpContext.coerce
函数改变为数字 – 如果id
只包含数字字符。
为了解决这个问题,我定义了SampleModel.findByIdCustom
并创build了另一个远程方法如下:
SampleModel.js
SampleModel.findByIdCustom = function(id, filter, cb) { SampleModel.findById(id, filter, cb); } //Define remote method SampleModel.remoteMethod( 'findByIdCustom', { description: 'Find a model instance by id from the data source.', accessType: 'READ', accepts: [ { arg: 'id', type: 'string', description: 'Model id', required: true, http: {source: 'path'}}, { arg: 'filter', type: 'object', description: 'Filter defining fields and include'} ], returns: {arg: 'data', type: 'user', root: true}, http: {verb: 'get', path: '/:id'}, rest: {after: SampleModel.convertNullToNotFoundError}, isStatic: true } ); //disable built-in remote method SampleMethod.disableRemoteMethod('findById', true);
谢谢,
只需将idInjection
设置为false
(这样loopback不会自动将id属性添加到您的模型中),然后使用以下参数定义一个属性:
{ "idInjection": false, "properties": { "id": { "type": "string", "id": true, "generated": true } } }