当uuid类型可选字段为null时,如何正确发起数据查询请求?
解决UUID可选字段为null时的查询语法错误
问题根源
你遇到的invalid syntax for uuid type: "null"错误,是因为request.body.parent传入的是字符串"null",而非JavaScript原生的null值。ORM会将这个字符串当作UUID格式的参数去解析,显然不符合UUID的语法规则,因此抛出报错。
解决方案
方法1:预处理参数,转换为真实null
先判断并转换request.body.parent的值,把字符串"null"或空值转为原生null:
// 预处理parent参数 const parentParam = request.body.parent === "null" || !request.body.parent ? null : request.body.parent; const current_file = await this.fileService.findOne({ relations: ['user', 'parent'], where: { name: file.originalname, user: current_user.user_id, parent: parentParam, }, });
方法2:动态构建查询条件(适配TypeORM等ORM)
如果使用的是TypeORM,可以利用IsNull()方法明确查询parent为null的情况,动态组装where条件:
// 记得导入IsNull import { IsNull } from "typeorm"; // 基础查询条件 const whereOpts = { name: file.originalname, user: current_user.user_id, }; // 根据parent参数添加对应条件 if (request.body.parent && request.body.parent !== "null") { whereOpts.parent = request.body.parent; } else { whereOpts.parent = IsNull(); } const current_file = await this.fileService.findOne({ relations: ['user', 'parent'], where: whereOpts, });
这两种方法都能避免把字符串"null"传入UUID类型的查询字段,确保参数类型符合ORM的要求。
内容的提问来源于stack exchange,提问作者Nonsense
相关产品推荐
相关产品推荐

