Apollo Server中DataSource子类UserAPI的this.store为undefined问题求助
问题根因及解决方案
构造函数参数名不匹配
你定义UserAPI构造函数时解构的是{ store }参数,但实例化UserAPI时传入的是{ models },参数名完全不匹配,导致this.store从初始化阶段就为undefined。
修改方案:二选一即可:- 把实例化代码调整为
new UserAPI({ store: models }) - 把构造函数参数调整为
constructor({ models }) { this.store = models }
- 把实例化代码调整为
models模块导出错误
你在models定义文件末尾写了两行module.exports:
module.exports=models module.exports=sequelize
后一行的导出会直接覆盖前一行,导致你外部导入的models变量实际上是sequelize实例,而非你定义的包含User、Trips的模型对象。
修改方案:调整为合并导出即可:
module.exports = { sequelize, models }
引入时按需解构:const { models } = require('./你的models文件路径')
- 模型调用大小写不匹配
你在UserAPI的findOrCreateUser方法中调用的是this.store.user.findOrCreate,但定义models对象时,用户模型的key是大写的User,大小写不匹配会导致后续调用时找不到模型报错。
修改方案:调整为this.store.User.findOrCreate即可。
内容的提问来源于stack exchange,提问作者Peter Malik
相关产品推荐
相关产品推荐

