gpt4 book ai didi

javascript - Loopback - 远程方法以及扁平化相关模型查询结果

转载 作者:行者123 更新时间:2023-12-03 01:12:27 26 4
gpt4 key购买 nike

我正在使用 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 Explorer 调用返回时,上述内容有效;

{
"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"
}, ...

我已经采取了扁平化客户端服务中的返回值的方法,但这只是开发中的临时解决方案。有关如何在远程方法中执行此操作的任何指导吗?

最佳答案

需要使用.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)
})
});
};

关于javascript - Loopback - 远程方法以及扁平化相关模型查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52160086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com