Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize: create is not a function when model is generated from migration

I created this model from sequelize CLI

models/society.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Society = sequelize.define('Society', {
    code: DataTypes.STRING,
    name: DataTypes.STRING,
    description: DataTypes.STRING
  }, {});
  Society.associate = function(models) {
    // associations can be defined here
  };
  return Society;
};

Then this is my index.js file for configurations

'use strict'

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const api = require('./routes')

app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.use('/api', api)

const port = process.env.PORT || 3000


app.listen(port, ()=>{
    console.log(`API REST running on http://localhost:${port}`)
})

The part of routes is this

routes/index.js

'use strict'

const express = require('express')
const api = express.Router()

const SocietyCtrl = require('../controllers/society')
api.post('/society', SocietyCtrl.createSociety)

module.exports = api

And finally it's just the controller controllers/society.js

'use strict'

const Society = require('../models/society')

function createSociety(req, res){
    console.log('POST /api/society/')
    Society.create(req.body).then(created =>{
        res.status(200).send({society: created})
    })
}

module.exports = {
    createSociety
}

The problem comes when I try to make POST, I get this following error:

Society.create is not a function

Can you tell me what I'm doing wrong?

like image 299
Sergio Laureano Avatar asked Feb 14 '20 05:02

Sergio Laureano


1 Answers

This problem is not related to migration, however to solve this problem you have to do two steps:

1) Add new file in models directory called index.js which contain the following code

NOTE: make sure to edit sequelize config (with your environment) which starts in line 9 and ends in line 13 in file below (models/index.js)

'use strict';

const Sequelize = require('sequelize');
const fs = require('fs');
const path = require('path');
const basename = path.basename(__filename);

const db = {};

const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  port: 3066,
  dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
});

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

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

module.exports = db;

2) in controllers/society.js file do the following

  • replace const Society = require('../models/society'); with const db = require('../models/index'); or const db = require('../models');
  • replace Society.create with db.Society.create

like this:

'use strict'

const db = require('../models');

function createSociety(req, res){
    console.log('POST /api/society/');
    db.Society.create(req.body).then(created =>{
        res.status(200).send({society: created})
    });
}

module.exports = {
    createSociety
}

To learn more I recommend you to check a github repository called express-example which developed by official sequelize team

like image 117
Amjed Omar Avatar answered Sep 20 '22 12:09

Amjed Omar