为何调用knex.ref时会出现‘ref is not a function’错误?
Knex调用ref方法报'ref is not a function'的解决办法
你遇到的问题核心是调用ref的方式不对,结合你的代码情况,原因和解决办法如下:
错误原因分析
你的knex.js导出的是经过.withSchema("appschema")包装后的查询构建器实例,这个包装后的对象本身没有ref方法;而你尝试的直接调用knex.ref()或Knex.ref(),若存在版本兼容或导入方式问题,也会触发报错。
正确的调用方式
方式1:从已有的数据库实例获取根Knex对象调用ref
你导出的包装实例保留了对原始Knex实例的引用,可通过database.knex访问并调用ref:
const database = require("../knex.js"); async function getResults() { const result = await database.from("table").select(database.knex.ref("id").as("table_id")); }
方式2:直接从Knex模块导入并调用静态ref方法
确保导入Knex核心模块后,调用其静态ref方法(适用于Knex v1.0+版本):
const database = require("../knex.js"); const Knex = require("knex"); async function getResults() { const result = await database.from("table").select(Knex.ref("id").as("table_id")); }
方式3:修改knex.js的导出结构(可选)
若需要频繁使用ref,可在knex.js中同时导出原始Knex实例和带schema的实例:
const knexInstance = knex({ client: "pg", connection: connectionString, pool: { min: 2, max: 10, }, debug: isDevelopment, }); const database = knexInstance.withSchema("appschema"); module.exports = { database, knexInstance };
之后在业务代码中直接使用导出的knexInstance.ref():
const { database, knexInstance } = require("../knex.js"); async function getResults() { const result = await database.from("table").select(knexInstance.ref("id").as("table_id")); }
额外注意点
- 检查Knex版本:若使用v0.90以下的旧版本,
ref方法的位置可能不同,建议升级到v1.x或v2.x稳定版。 - 你的示例代码都缺失一个闭合括号
),需补上避免语法错误。
内容的提问来源于stack exchange,提问作者codlix
相关产品推荐
相关产品推荐

