【发布时间】:2018-05-12 07:00:27
【问题描述】:
我有这种奇怪的行为。
我有一个用户模型和一个客户模型。用户有很多客户。
我正在使用这个文档:http://docs.sequelizejs.com/manual/tutorial/associations.html
当我运行服务器时,Sequelize 抛出 TypeError: User.hasMany is not a function
节点版本: 8.9.1
方言: postgres
数据库版本: Postgres 10
续集版本: 4.22.15
以下文件都在同一个文件夹中
user.js 模型
const Sequelize = require('sequelize');
const db = require('../index.js'); //This is an instance of new Sequelize(...)
const tableName = 'users';
const User = db.define('user', {
firstName: {
type: Sequelize.STRING(50),
allowNull: false,
validate: {
notEmpty: true
}
},
lastName: {
type: Sequelize.STRING(50),
allowNull: false,
validate: {
notEmpty: true
}
},
username: { //Username will be the email
type: Sequelize.STRING(80),
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
isAdmin: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
},
isActive: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
}
}, { tableName });
module.exports = User;
client.js 模型
'use strict'
const Sequelize = require('sequelize');
const db = require('../index.js');
const instanceMethods = {
toJSON() {
const values = Object.assign({}, this.get());
return values;
},
};
const Client = db.define('clients', {
ibid: {
type: Sequelize.BIGINT,
allowNull: true,
defaultValue: null
},
firstName: {
type: Sequelize.STRING(50),
allowNull: false,
validate: {
notEmpty: true
}
},
lastName: {
type: Sequelize.STRING(50),
allowNull: false,
validate: {
notEmpty: true
}
},
agreementSigned: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
},
totalBalance: {
type: Sequelize.DECIMAL(11,2),
allowNull: true,
defaultValue: null
},
currentAllocation: {
type: Sequelize.STRING,
allowNull: true,
defaultValue: null
}
}, { instanceMethods });
module.exports = Client;
index.js 模型
'use strict';
const User = require('./user')
const Client = require('./client');
User.hasMany(Client);
Client.belongsTo(User);
module.exports = {User, Client};
【问题讨论】:
-
在 user.js 中你没有导出用户
module.exports = User; -
@Molda 对不起,我没有复制文件的最终版本,但是是的,我正在正确导出用户模型
标签: javascript node.js postgresql express sequelize.js