Prisma操作MongoDB时$gte/$lte类型不匹配报错排查
解决Prisma地理位置范围查询的类型不匹配错误
问题原因
你遇到的Type '{ $gte: number; $lte: number; }' is not assignable to type 'number'错误,核心原因是用了MongoDB原生的$gte/$lte操作符,但Prisma Client的查询语法中,数值类型的范围查询需要使用不带$前缀的gte/lte驼峰式操作符,两者语法规范不匹配导致类型校验失败。
修正后的代码
async getStaffsByDutyAndLocation(req: Request, res: Response) { const { duty, location } = req.body; try { // 校验地理位置参数合法性 if (!location?.long || !location?.lat) { return res.status(400).json({ error: '缺少合法的地理位置参数' }); } const minLong = parseFloat(location.long) - 0.5; const maxLong = parseFloat(location.long) + 0.5; const minLat = parseFloat(location.lat) - 0.5; const maxLat = parseFloat(location.lat) + 0.5; // 校验解析后的数值有效性 if (isNaN(minLong) || isNaN(maxLong) || isNaN(minLat) || isNaN(maxLat)) { return res.status(400).json({ error: '地理位置参数格式错误' }); } const staffs = await StaffController.prisma.staff.findMany({ where: { duty, location: { long: { gte: minLong, lte: maxLong, }, lat: { gte: minLat, lte: maxLat, }, }, }, }); return res.status(200).json(staffs); } catch (error) { console.error('查询员工失败:', error); return res.status(500).json({ error: '服务器内部错误' }); } }
关键说明
- Prisma Client针对数值类型的范围查询,统一使用
gte(大于等于)、lte(小于等于)、gt(大于)、lt(小于)这类不带$的操作符,这是Prisma的标准语法,和MongoDB原生查询的$前缀写法不同。 - 额外添加了参数校验和错误处理,避免因前端传入非法参数导致的解析失败或查询异常,提升接口健壮性。
内容的提问来源于stack exchange,提问作者T.Courage
相关产品推荐
相关产品推荐

