【问题标题】:express & sequalize Converting circular structure to JSONexpress 和 sequelize 将循环结构转换为 JSON
【发布时间】:2019-06-11 11:20:55
【问题描述】:

我有一个异步 Sequelize 函数

async getTrips() {
    let trips = await Trip.findAll({
        order: [['id']]
    });

    const data  = trips.map(trip => ({
        ...trip,
        milestones: async () => await Milestone.findAll({
            where: {
                trips_id: trip.id
            }
        }),
        vendor_charges: async () => await VendorCharge.findAll({
            where: {
                trips_id: trip.id
            }
        }),
        trip_notes: async () => await TripNote.findAll({
            where: {
                trips_id: trip.id
            }
        }),
        pieces: async () => await Pieces.findAll({
            where: {
                trips_id: trip.id
            }
        })
    }))
    return data
}

然后在快速路由器中运行

tripsRouter.get('/getAllTrips', (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty())
        return res.status(422).json(errors.array())
    tripsService.getTrips()
    .then(trips =>
        res.status(200).json({
            exception: false,
            payload: trips
        })
    );
})

这似乎在执行时产生“将循环结构转换为 JSON”错误

这是错误堆栈:

(node:9322) UnhandledPromiseRejectionWarning: TypeError: 将循环结构转换为 JSON 在 JSON.stringify() 在 o.getTrips.then.e (/home/sandra/development/lakefrontcargo-v2/dist/index.js:1:57753) 在 (节点:9322)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝编号:1) (节点:9322)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。 [nodemon] 因更改而重启...

【问题讨论】:

  • findAll() 解析为 Models 数组,而不是普通对象。这些模型具有各种内部属性和循环引用,在调用 res.json() 时,它们无法通过 express 转换为普通对象(通过 JSON)。解决方案是为每个findAll() 调用删除这些引用,例如so= (await Model.findAll()).map((entry) => entry.toJSON())
  • 我已经有一段时间没有搞砸它们了,但是关于循环序列化错误,Douglas Crockford 有一个解决方案,ResurectJS 对我也很有效

标签: javascript node.js express sequelize.js


【解决方案1】:

由于map 返回一系列承诺,所以我建议您使用Promise.all 等待所有承诺完成。

const data  = Promise.all ( trips.map(trip => ({
    ...trip,
    milestones: async () => await Milestone.findAll({
        where: {
            trips_id: trip.id
        }
    }),
    vendor_charges: async () => await VendorCharge.findAll({
        where: {
            trips_id: trip.id
        }
    }),
    trip_notes: async () => await TripNote.findAll({
        where: {
            trips_id: trip.id
        }
    }),
    pieces: async () => await Pieces.findAll({
        where: {
            trips_id: trip.id
        }
    })
})) );


return await data;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 2017-04-03
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多