我正在使用Loopback 3开发应用程序。我已经在ServiceEvaluation模型上创建了一个远程方法,以返回ServiceEvaluations和服务模型中相关属性的列表。
ServiceEvaluation.evaluationList = function(cb) {
ServiceEvaluation.find({
fields: {
status: true,
createdAt: true,
serviceId: true
},
include: {
relation: 'rel_ServiceEval_Service',
scope: {
fields: {
serviceName: true,
supplierId: true
}
}
}
}, function(err, response) {
cb(null, response);
});
};
从API资源管理器返回时,上述方法有效;
{
"list": [
{
"status": "Draft",
"serviceId": "5b8e215d81c76325b409b960",
"createdAt": "2018-09-04T06:08:29.623Z",
"rel_ServiceEval_Service": {
"serviceName": "Workplace software and SaaS",
"id": "5b8e215d81c76325b409b960",
"supplierId": "5b8e215d81c76325b409b949"
}
}, ...
但是,我不想返回带有嵌入式对象的对象数组,而是想返回一个展平对象的数组以显示在数据网格中。以下是尝试这样做的方法。
ServiceEvaluation.evaluationList = function(cb) {
ServiceEvaluation.find({
fields: {
status: true,
createdAt: true,
serviceId: true
},
include: {
relation: 'rel_ServiceEval_Service',
scope: {
fields: {
serviceName: true,
supplierId: true
}
}
}
}, function(err, response) {
var responseLength = response.length;
var myEntry = {};
var myList = [];
for (var i = 0; i < responseLength; i++) {
myEntry.status = response[i].status;
myEntry.createdAt = response[i].createdAt;
myEntry.serviceName = response[i].rel_ServiceEval_Service.serviceName;
myEntry.supplierId = response[i].rel_ServiceEval_Service.supplierId;
myList.push(myEntry);
}
cb(null, myList);
});
};
其结果是,远程方法似乎找不到rel_ServiceEval_Service中的字段。
{
"list": [
{
"status": "Draft",
"createdAt": "2018-09-04T06:20:40.889Z"
}, ...
我已经求助于在客户端的服务中平整返回值,但这只是在开发环境中的临时解决方案。关于如何使用远程方法执行此操作的任何指导?
答案 0 :(得分:1)
您需要使用.toJSON()序列化返回的数据:
ServiceEvaluation.evaluationList = function(cb) {
ServiceEvaluation.find({
fields: {
status: true,
createdAt: true,
serviceId: true
},
include: {
relation: 'rel_ServiceEval_Service',
scope: {
fields: {
serviceName: true,
supplierId: true
}
}
}
}, function(err, response) {
var myEntry = {};
var myList = [];
async.map(response, function(singleItem,callback){
serializedSingleItem = singleItem.toJSON()
var myEntry = {status: serializedSingleItem.status, createdAt: serializedSingleItem.createdAt, serviceName: serializedSingleItem["rel_ServiceEval_Service"]["serviceName"], supplierId: serializedSingleItem["rel_ServiceEval_Service"]["supplierId"]}
callback(null, myEntry)
}, function(err, myList){
cb(null, myList)
})
});
};