valtlfelipe / hapi-sequelizejs

A hapi.js plugin to connect with Sequelize ORM
MIT License
62 stars 17 forks source link

Plugin not detecting models #4

Closed MrDHat closed 7 years ago

MrDHat commented 7 years ago

I am using postgres with sequelize. Here is what my code looks like:

server.register([
  {
    register: require('hapi-sequelizejs'), // eslint-disable-line global-require
    options: {
      name: Config.db.name,
      models: ['./models/*.js'],
      sequelize: new Sequelize(Config.db.name, Config.db.username, Config.db.password, {
        host: Config.db.host,
        dialect: 'postgres',
      }),
      sync: true,
    },
  },
])

When I log req.server.plugins['hapi-sequelizejs'][Config.db.name].getModels() I get an empty object. Here is what my model definition looks like:

module.exports = (sequelize, DataTypes) => {
  const schema = {
    id: {
      type: DataTypes.UUIDV4,
      primaryKey: true,
    },
    name: DataTypes.STRING,
    email: DataTypes.STRING,
    gender: DataTypes.ENUM('male', 'female', 'other'),
  };
  return sequelize.define('User', schema);
};

Not sure what the problem is here.

P.S. I have confirmed that the location of the models glob is correct by manually using node-glob.

antonsamper commented 7 years ago

Try updating your models property value to:

models: [`${__dirname}/models/*.js`],

Or if your models are in separate sub folders e.g. models/user/index.js, then try this:

models: [`${__dirname}/models/**/*.js`],

If the above doesn't work, can you share your folder structure?

MrDHat commented 7 years ago

Ah, that worked. Thanks!

rogeriomq commented 7 years ago

I solved with: models: ['**/sequelize/models/**.js'],

arbisyarifudin commented 1 year ago

Hi, I am facing the same issue here.

Here is my code:

const sequelize = new Sequelize('mydatabasename', 'postgres', 'root', {
    host: 'localhost',
    port: '5432',
    dialect: 'postgres'
  })
  await server.register([
    {
      plugin: HapiSequelize,
      options: [
        {
          name: 'db', // identifier
          models: [__dirname + '/models/**/*.js'], // paths/globs to model files
          // ignoredModels: [__dirname + '/models/**/*.js'], // OPTIONAL: paths/globs to ignore files
          sequelize: sequelize, // sequelize instance
          sync: true, // sync models - default false
          // forceSync: false // force sync (drops tables) - default false
        }
      ]
    }
  ])

  console.log(HapiSequelize.instances.getModel('db','Contact')) // return error 

it's return Error: hapi-sequelizejs cannot find the Contact model

here is my directory structure: image

and this is my contact model: image

valtlfelipe commented 1 year ago

@arbisyarifudin in which file did you instantiated the sequelize? Also could you try to export the model using module.exports?