Kyle U
Kyle U

Reputation: 305

Sequelize - TypeError: Cannot read property 'define' of undefined

EDIT: There was a line present in my code that was left out of my example, it has been added and labeled with a comment.

I'm setting up a server for a new project and attempting to use Sequelize for the first time since v5. Upon running my server, this error is thrown.

/Users/me/dev/projects/my-project/node_modules/sequelize/lib/model.js:730
    options = Utils.merge(_.cloneDeep(globalOptions.define), options);
                                                    ^

TypeError: Cannot read property 'define' of undefined
    at Function.init (/Users/me/dev/projects/my-project/node_modules/sequelize/lib/model.js:730:53)
    at Object.<anonymous> (/Users/me/dev/projects/my-project/src/server/db/models/user.js:16:6)
    at Module._compile (internal/modules/cjs/loader.js:736:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:747:10)
    ...

The error occurs during the invocation of my model definition initialization:

const sequelize = require("../_db");

...

console.log('this runs');

class User extends Sequelize.Model {} // edit: this line was here
User.init(
  {
    avatar: {
      default: {
        type: Sequelize.URL,
        value: defaultAvatar
      },
      type: Sequelize.STRING
    },
    email: {
      allowNull: false,
      type: Sequelize.STRING,
      unique: true
    },
    id: {
      defaultValue: Sequelize.UUIDV1,
      primaryKey: true,
      type: Sequelize.UUID
    },
    name: {
      type: Sequelize.STRING
    },
    password: {
      allowNull: false,
      get() {
        return () => this.getDataValue("password");
      },
      type: Sequelize.STRING
    },
    salt: {
      get() {
        return () => this.getDataValue("salt");
      },
      type: Sequelize.STRING
    }
  },
  { sequelize, modelName: "user" }
);

console.log('this doesn't);

This is pretty cryptic to me, I'm not quite sure what could have gone wrong.

Upvotes: 2

Views: 5235

Answers (1)

th1nkful
th1nkful

Reputation: 118

You need to include the class definition for user. I can't see it in the code you've provided. This would explain why the error says it is from "undefined"

i.e.

const Model = Sequelize.Model;    
class User extends Model {}

You could do:

class User extends Sequelize.Model {}

See here: https://sequelize.org/master/manual/models-definition.html

Additionally, it looks like you are using Sequelize's default model loader, you will need to have that model defined inside a

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define("User", {

  });

  return User
}; 

Upvotes: 1

Related Questions