问题
Trying to play around with Sequelize in a node.js webserver.
I have initialised the Sequelize connection pool in index.js like so
index.js
const config = require('./config/config');
const app = require('./config/express');
const Sequelize = require('sequelize');
const sequelize = new Sequelize(config.mysql.database, config.mysql.user, config.mysql.pass, {
host: config.mysql.host,
dialect: 'mysql',
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.'); // eslint-disable-line no-console
})
.catch((err) => {
console.error('Unable to connect to the database:', err); // eslint-disable-line no-console
});
module.exports = { app, sequelize };
user.js model
const sequelize = require('sequelize');
const DataTypes = require('mysql');
/**
* User model
*/
const User = sequelize.define('user', {
id: {
type: DataTypes.INTEGER,
},
name: {
type: DataTypes.STRING,
},
email: {
type: DataTypes.STRING,
},
lastEmail: {
type: DataTypes.TIME,
}
});
When trying to start the server I get the following error
TypeError: sequelize.define is not a function ... user.js
I am guessing the sequelize object is not being made global, however I tested the connection before creating the model and it was fine.
回答1:
In user.js you are trying to use an instance method .define()
on something that is not an instance. In index.js you do create an instance by calling the constructor, but that is not available in user.js. The solution here really depends on what you are trying to accomplish and how you want to organize your code. Normally index.js is the entry point to your application, so it is a little unusual to be exporting app
and sequelize
from there, but if that is what you want to do, then in your user.js file you could require index.js, and use the sequelize instance that you defined there. In that case, your index.js would stay the same and User.js might just have a change in the first require
:
const sequelize = require('index.js').sequelize;
const DataTypes = require('mysql');
/**
* User model
*/
const User = sequelize.define('user', {
id: {
type: DataTypes.INTEGER,
},
name: {
type: DataTypes.STRING,
},
email: {
type: DataTypes.STRING,
},
lastEmail: {
type: DataTypes.TIME,
}
});
I'm not necessarily recommending this approach, because, again, it really depends on what you are trying to do (I think maybe you are leaving out some of your code?), but it does show one way to use the instantiated sequelize object from index.js in user.js
回答2:
I was having the same problem..and It works for me..
module.exports = (DataTypes , sequelize) => {
const User = sequelize.define('user', {
id: {
type: DataTypes.INTEGER,
},
name: {
type: DataTypes.STRING,
},
email: {
type: DataTypes.STRING,
},
lastEmail: {
type: DataTypes.TIME,
}
})
return User;
};
来源:https://stackoverflow.com/questions/49470508/sequelize-define-is-not-a-function