MySQL 8中Geometry类型查询触发AsText不存在错误的解决方法
解决MySQL 8 + TypeORM Geometry列查询报错(AsText函数不存在)
问题根源
MySQL 8.0已移除AsText()函数(该函数在5.7.6版本被废弃),但旧版本TypeORM处理Geometry类型时仍默认调用此废弃函数,导致查询触发ER_SP_DOES_NOT_EXIST错误。
解决方案
1. 升级TypeORM及相关依赖(优先推荐)
你当前使用的@nestjs/typeorm@9.0.1对MySQL 8的Geometry类型支持不完善,升级到适配版本可自动修复函数调用逻辑:
- 升级
@nestjs/typeorm和typeorm(两者版本需匹配,建议参考官方兼容表):
npm install @nestjs/typeorm@^10.0.0 typeorm@^0.3.0 --save
- 移除冗余的
mysql8依赖(该包已过时,与mysql2存在冲突):
npm uninstall mysql8
2. 自定义列转换逻辑(不升级依赖时的临时方案)
在实体类的Geometry列上,通过transformer属性替换为MySQL 8支持的ST_AsText()和ST_GeomFromText()函数:
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; @Entity('users') export class User { @PrimaryGeneratedColumn() id: number; @Column({ type: 'geometry', nullable: true, transformer: { // 写入数据库时将WKT字符串转为Geometry对象 to: (value: string) => value ? `ST_GeomFromText('${value}')` : null, // 从数据库读取时将Geometry对象转为WKT字符串 from: (value: any) => `ST_AsText(${value})`, }, }) location: string; }
3. 确认数据库驱动配置
确保TypeORM连接配置使用mysql2驱动,避免旧驱动的兼容性问题:
// app.module.ts中的TypeORM配置 TypeOrmModule.forRoot({ type: 'mysql', host: 'localhost', port: 3306, username: 'your_username', password: 'your_password', database: 'your_database', entities: [User], synchronize: false, // 生产环境务必关闭此选项 driver: require('mysql2'), }),
内容的提问来源于stack exchange,提问作者Martin54
相关产品推荐
相关产品推荐

