Prisma查询BigInt类型数据时JSON序列化报错的解决咨询
解决Prisma查询BigInt时的JSON序列化错误
问题核心是Prisma返回的原生BigInt类型无法被JSON.stringify默认序列化,导致抛出类型错误。以下是几种可行的解决方法:
方法1:查询后手动转换BigInt字段
在获取查询结果后,遍历数据将BigInt转为Number或String(数值超出2^53-1时建议用String避免精度丢失):
const reports = await prismaService.instant_reports.findMany({ skip: 0, take: 30, }); // 转换为Number(适用于数值在安全范围内的场景) const serializedReports = reports.map(report => ({ ...report, id: Number(report.id), timestamp: report.timestamp ? Number(report.timestamp) : null, client_id: report.client_id ? Number(report.client_id) : null, uniq_users: report.uniq_users ? Number(report.uniq_users) : null, })); // 转换为String(适用于大数值场景,避免精度丢失) const serializedReports = reports.map(report => ({ ...report, id: report.id.toString(), timestamp: report.timestamp ? report.timestamp.toString() : null, client_id: report.client_id ? report.client_id.toString() : null, uniq_users: report.uniq_users ? report.uniq_users.toString() : null, }));
方法2:全局修改BigInt的序列化逻辑
在项目入口文件(如main.ts)中添加全局处理,让所有BigInt自动支持JSON序列化:
// 全局配置BigInt的JSON序列化规则 (BigInt.prototype as any).toJSON = function() { return this.toString(); // 或根据需求改为Number(this) };
此方法一劳永逸,但需注意全局修改可能影响其他依赖BigInt原生行为的代码。
方法3:使用Prisma的cast功能在查询时转换
通过select字段指定类型转换,直接在数据库查询阶段将BigInt转为字符串(需Prisma版本支持该功能):
const reports = await prismaService.instant_reports.findMany({ skip: 0, take: 30, select: { id: { cast: { to: 'String' } }, created_at: true, updated_at: true, deleted_at: true, timestamp: { cast: { to: 'String' } }, client_id: { cast: { to: 'String' } }, uniq_users: { cast: { to: 'String' } }, }, });
内容的提问来源于stack exchange,提问作者bluepuper
相关产品推荐
相关产品推荐

