luhfluh luhfluh - 4 months ago 22
Node.js Question

sequelize DataTypes TypeError: Cannot read property 'INTEGER' of undefined

I have a sequelize DataTypes.INTEGER issue when defining a model. Im following an example in ebook titled "Building APIs with Node.js". Im a greenhorn trying to grasp express and sequelize. Any help much appreciated. Thanks.

error details:

> /home/xxx/workspace/ntask-api/models/tasks.js:9
> type: DataTypes.INTEGER,
> ^ TypeError: Cannot read property 'INTEGER' of undefined
> at Function.module.exports (/home/xxx/workspace/ntask-api/models/tasks.js:9:21)
> at Consign.into (/home/xxx/workspace/ntask-api/node_modules/consign/lib/consign.js:239:17)
> at Object.<anonymous> (/home/xxx/workspace/ntask-api/index.js:13:5)
> at Module._compile (module.js:456:26)
> at Object.Module._extensions..js (module.js:474:10)
> at Module.load (module.js:356:32)
> at Function.Module._load (module.js:312:12)
> at Function.Module.runMain (module.js:497:10)
> at startup (node.js:119:16)
> at node.js:902:3


code sample below in


/models/tasks.js


:

> module.exports = function(sequelize, DataTypes){
> //console.log(DataTypes.INTEGER);
> const Tasks = sequelize.define("Tasks", { id: {
> type: DataTypes.INTEGER,
> primaryKey: true,
> autoIncrement: true }, title: {
> type: DataTypes.STRING,
> allowNull: false,
> validate: { notEmpty: true
> } }, done: {
> type: DataTypes.BOOLEAN,
> allowNull: false,
> defaultValue: false }
> },
> { classMethods:{
> associate: function(models){ Tasks.belongsTo(models.Users, {
> onDelete: "CASCADE",
> foreignKey: { allowNull: false
> } });
> } }
> });
> return Tasks; };


I also tried the suggestion from TypeError: object is not a function when defining models in NodeJs using Sequelize by adding this to the top of models/tasks.js file but same error.


var DataTypes = require('sequelize/lib/data-types');

Answer

sequelize changes a lot, so the answer of stackoverflow might not be correct.

If you check out the sequelize doc (link)

They start to use Sequelize.XXXX instead

here is the example from the doc

var Project = sequelize.define('project', {
  title: Sequelize.STRING,
  description: Sequelize.TEXT
})

var Task = sequelize.define('task', {
  title: Sequelize.STRING,
  description: Sequelize.TEXT,
  deadline: Sequelize.DATE
})

hence, you have 2 ways to achieve that

  1. require('sequelize') in every model file
  2. require('sequelize') in the index file and pass it to every model file
Comments