Loopback中如何定义模型以从customer表返回指定JSON结构?
嘿,这个需求我之前做项目时刚好碰到过!要实现你要的这种以客户ID为键的JSON结构,得拆成两步来搞:先正确定义Customer模型,再调整返回格式——毕竟Loopback默认查询返回的是数组,而你要的是键值对映射。
第一步:定义Customer模型
首先在common/models/customer.json里定义模型的属性,完全匹配你需要的字段,注意ID字段要设为字符串类型(因为你的示例里ID是带引号的字符串格式):
{ "name": "Customer", "base": "PersistedModel", "idInjection": true, "properties": { "address": { "type": "string", "default": "" }, "city": { "type": "string", "default": "" }, "company": { "type": "string", "default": "" }, "email": { "type": "string", "default": "" }, "forename": { "type": "string", "required": true }, "moreinfo": { "type": "string", "default": "" }, "note": { "type": "string", "default": "" }, "postalcode": { "type": "string", "default": "" }, "surname": { "type": "string", "required": true }, "tel": { "type": "string", "default": "" } }, "validations": [], "relations": {}, "acls": [], "methods": {} }
这里我给空值字段加了default: "",这样返回时就不会出现null,和你的示例保持一致。如果不需要默认值也可以去掉,根据实际需求调整。
第二步:把查询结果转成ID为键的对象
Loopback默认的find()方法返回的是数组,所以我们需要修改返回格式。这里有两种常用方案:
方案一:自定义远程方法(推荐,更灵活)
在common/models/customer.js里添加一个自定义的远程方法,专门返回你要的结构:
module.exports = function(Customer) { // 自定义远程方法:获取客户映射 Customer.getCustomerMap = function(callback) { Customer.find({}, function(err, customers) { if (err) return callback(err); // 把数组转成以ID为键的对象 const customerMap = {}; customers.forEach(cust => { // 把ID从对象中提取出来当键,剩余属性作为值 const { id, ...rest } = cust.toJSON(); customerMap[id] = rest; }); callback(null, customerMap); }); }; // 注册远程方法的路由和返回格式 Customer.remoteMethod('getCustomerMap', { returns: { arg: 'customers', type: 'object', root: true }, http: { path: '/map', verb: 'get' } }); };
之后你访问GET /api/customers/map就能得到你要的JSON结构了。
方案二:修改默认find方法的返回结果(用afterRemote钩子)
如果你想让默认的GET /api/customers也返回这种结构,可以用afterRemote钩子来修改结果:
module.exports = function(Customer) { // 拦截find方法的返回结果 Customer.afterRemote('find', function(ctx, result, next) { if (Array.isArray(result)) { const customerMap = {}; result.forEach(cust => { const { id, ...rest } = cust.toJSON(); customerMap[id] = rest; }); // 替换返回结果 ctx.result = customerMap; } next(); }); };
这样调用默认的find接口时,就会自动返回你要的键值对结构了。
注意:如果你的ID是数字类型(比如数据库里存的是BigInt),Loopback会自动转成字符串,所以不用担心键的格式问题——和你示例里的"1521544526409"格式完全匹配。
内容的提问来源于stack exchange,提问作者Hardik
相关产品推荐
相关产品推荐

