远程方法,查询和循环关系数据
Remote method, query and loop over relation data
我有一个模型,Bill,hasMany Orders.
如果我在 Bill 中编写了一个远程方法,我如何查询一个账单并遍历它的订单?
bill.json
{
"name": "bill",
...
"relations": {
"orders": {
"type": "hasMany",
"model": "order",
"foreignKey": "orderId"
}
}
bill.js
Bill.doLoop = async function(id, body, callback) {
let bill = await Bill.findById(id, {include: ['orders']})
for (let order of bill.orders) {
console.log(order);
}
}
如果我这样做,我会收到以下错误:
Unhandled error for request POST /api/bills/1/doLoop : TypeError: bill.orders[Symbol.iterator] is not a function
如果我将 bill 转换为 JSON 字符串并返回,则可以访问订单,但这感觉非常脏:
let billJson = JSON.parse(JSON.stringify(bill))
for (let order of billJson.orders) {
console.log(order);
}
我在 Include filter - Access included objects 的 Loopbacks 文档中找到了答案:
In the Node.js API, call toJSON() to convert the returned model instance with related items into a plain JSON object.
更新代码使其有效:
Bill.doLoop = async function(id, body, callback) {
let bill = await Bill.findById(id, {include: ['orders']})
for (let order of bill.toJSON().orders) {
console.log(order);
}
}
我有一个模型,Bill,hasMany Orders.
如果我在 Bill 中编写了一个远程方法,我如何查询一个账单并遍历它的订单?
bill.json
{
"name": "bill",
...
"relations": {
"orders": {
"type": "hasMany",
"model": "order",
"foreignKey": "orderId"
}
}
bill.js
Bill.doLoop = async function(id, body, callback) {
let bill = await Bill.findById(id, {include: ['orders']})
for (let order of bill.orders) {
console.log(order);
}
}
如果我这样做,我会收到以下错误:
Unhandled error for request POST /api/bills/1/doLoop : TypeError: bill.orders[Symbol.iterator] is not a function
如果我将 bill 转换为 JSON 字符串并返回,则可以访问订单,但这感觉非常脏:
let billJson = JSON.parse(JSON.stringify(bill))
for (let order of billJson.orders) {
console.log(order);
}
我在 Include filter - Access included objects 的 Loopbacks 文档中找到了答案:
In the Node.js API, call toJSON() to convert the returned model instance with related items into a plain JSON object.
更新代码使其有效:
Bill.doLoop = async function(id, body, callback) {
let bill = await Bill.findById(id, {include: ['orders']})
for (let order of bill.toJSON().orders) {
console.log(order);
}
}