如何使用DenoDB执行where查询?调用where方法报undefined错误如何解决?
问题原因分析
你遇到的TypeError - Cannot read properties of undefined (reading 'where')报错核心原因是DenoDB模型未完成数据库关联初始化:
看你的Users模型代码末尾,db.link([Users])和await db.sync()两行代码是注释状态:
db.link([Users])的作用是将自定义的Users模型和你初始化的数据库实例绑定,DenoDB只有完成绑定后才会给模型注入where、get、create等查询操作方法db.sync()的作用是同步模型定义到数据库,创建对应数据表(如果不存在的话)
这两行没有执行的情况下,Users模型上没有挂载查询相关的内置方法,调用Users.where自然会报错。
修复步骤
- 首先取消模型代码末尾两行的注释,注意如果是生产环境不要给
db.sync()加{drop: true}参数,否则会清空已有数据表:
db.link([Users]); await db.sync();
注意:db.sync()是异步操作,需要确保它执行完成后再启动接口服务,否则接口调用时模型仍未初始化完成
- 正确的where条件查询用法:
DenoDB的where查询支持两种常用写法:
- 单条件链式写法:
// 查询邮箱匹配的所有用户 const existing = await Users.where('email', body.email).get(); // 只查询第一条匹配的用户(判断用户是否存在的场景用这个性能更好) const existing = await Users.where('email', body.email).first();
- 多条件对象写法:
// 同时匹配多个字段 const existing = await Users.where({ email: body.email, status: 1 }).get();
- 链式多条件写法:
const existing = await Users.where('email', body.email).where('status', 1).get();
- 注册逻辑优化建议
判断用户是否存在的场景无需查询所有匹配结果,用first()更高效,修改后的业务代码参考:
async register(context: any) { const body = JSON.parse(await context.request.body().value); // 用first()只查第一条匹配数据,返回值是用户对象/ null const existing = await Users.where("email", body.email).first(); if (existing) { context.response.status = 400; return (context.response.body = { message: "User already exists" }); } const hashedPassword = await Users.hashPassword(body.password); const user = await Users.create({ email: body.email, hashedPassword, }); context.response.body = { message: "User created" }; }
内容的提问来源于stack exchange,提问作者chovy
相关产品推荐
相关产品推荐

