我正在尝试从dbController外包dbInit
函数的模型,因为我有多个模型使dbController变大。
所以我正在从initDb
呼叫db_controller.js
,它看起来像这样(我使用了文档http://docs.sequelizejs.com/manual/getting-started.html)
const userModel = require('../model/user')
const subjectModel = require('../model/subject')
const Sequelize = require('sequelize')
const seq = new Sequelize({
dialect: 'sqlite',
storage: './user.db'
})
async function initDb () {
await userModel.user.initUser()
await subjectModel.subject.initSubject()
userModel.user.userClass.hasMany(subjectModel.subject.subjectClass)
}
user.js
中的用户如下:
const Sequelize = require('sequelize')
const seq = new Sequelize({
dialect: 'sqlite',
storage: './user.db'
})
class User extends Sequelize.Model {
}
exports.user = {
initUser: initUser,
userClass: User
}
async function initUser () {
return new Promise(resolve => {
User.init(
// attributes
{
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false
}
},
// options
{
seq,
modelName: 'user'
}
)
resolve()
})
}
与subject.js
const Sequelize = require('sequelize')
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: './user.db'
})
class Subject extends Sequelize.Model {
}
exports.subject = {
initSubject: initSubject,
subjectClass: Subject
}
async function initSubject () {
return new Promise(resolve => {
Subject.init(
// attributes
{
name: {
type: Sequelize.STRING,
allowNull: false
}
},
// options
{
seq: sequelize,
modelName: 'subject'
}
)
resolve()
})
}
因此,当我尝试通过node db_controller.js
我收到此错误(缩短)
(node:12444) UnhandledPromiseRejectionWarning: Error: No Sequelize instance passed
at Function.init (D:\Git\ppb\node_modules\sequelize\lib\model.js:915:13)
at resolve (D:\Git\ppb\src\model\user.js:26:10)
at new Promise (<anonymous>)
at Object.initUser (D:\Git\ppb\src\model\user.js:25:10)
at initDb (D:\Git\ppb\src\controller\db_controller.js:18:24)
at Object.<anonymous> (D:\Git\ppb\src\controller\db_controller.js:45:1)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
非常感谢您提前提出任何建议!
答案 0 :(得分:1)
我认为您在选项中传递seq
而不是sequelize
很奇怪。
在http://docs.sequelizejs.com/处检查文档在示例中,我看到它们传递了属性sequelize
而不是seq
。
所以我建议更改:
{
seq: sequelize,
modelName: 'subject'
}
到
{
sequelize: sequelize,
modelName: 'subject'
}
答案 1 :(得分:1)
import database from 'path/some*.ts';
这是我在 express app.ts 中使用时的 init 数据库文件;同样在这个数据库文件中,我导出了 sequelize 实例;
import User from '../some/model/define/file';
数据库导入Sequelize后可以自动同步定义到模式,模型如下:
Class User extends Model {...}
User.define(...);
User.has or many();
这样可以解决问题:sequelize instance error。
点:在你的续集参考顺序后面!!!!