Nextjs and Sequelize - Cannot Import Models

Viewed 243

I have created a bunch of files using the sequelize CLI as per their docs here: enter link description here.

Both the pages and db folder reside in the root project directory.

My /pages/api/login.js file:

const models = require('/db/models/index')

export default async function handler(req, res) {
  
  console.log(models)

  res.status(200).json({ name: 'John Doe' })
}

My /db/models/index.js file:

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.js')[env];
const db = {};

/* Custom handler for reading current working directory */
const models = process.cwd() + '/db/models/' || __dirname;

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(models)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== 'index.js') && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    // const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    const model = require(path.join(models, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });


Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

My /db/models/user.js file:

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    static associate(models) {
    }
  }
  User.init({
    email: DataTypes.STRING,
    password: DataTypes.STRING,
    role: DataTypes.STRING,
    role: DataTypes.BOOLEAN
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};

However, when I make a call to /api/login via the frontend, I get the following error:

Error: Cannot find module '/Users/me/Desktop/Personal Projects/project/website/db/models/user.js'

Can someone please help me as to how to use sequelize with nextjs? I read their docs and scoured the net, but cannot find out what the problem is.

1 Answers

You can find clues here https://stackoverflow.com/a/73132197/6048105

But for your case here need to change in index.js:

const model = require(path.join(models, file))(sequelize, Sequelize.DataTypes);

change to

// "__dirname + '/../models/' + file" must always insert in require function
// if above value is use as const or other variable not gonna working
const model = require(__dirname + '/../db/models/' + file)(sequelize, Sequelize.DataTypes);

in your /pages/api/login.js

'use strict'

import {sequelize, User} from '../../../db/models/index';
sequelize.sync();

export default async function handler(req, res) {
  
  //better to check connection first
  try {
    await sequelize.authenticate();
  } catch (error) {
    return res.status(400).json({"message":"Unable to connect to the database:", error})
  }

  const users = await User.findAll(); //if you want to get all users datas

  res.status(200).json({users})
}

Suggestion :

in your /db/models/user.js its better to use lowercase table name to avoid trouble in the future, change :

modelName: 'User'

to

tableName: 'user'

but it's up to you :)

Related