salep
salep

Reputation: 1390

sequelize .create is not a function error

I'm getting Unhandled rejection TypeError: feed.create is not a function error and I can't understand why it occurs. What's the problem here?

Here's my code. I'm probably not doing something very fundamental here since I can't reach feed variable in routes/index.js.

If I add module.exports = feed; to my models file, I can reach it, but I have more than one models, so if I add additional models below the feed, they override it.

db.js

var Sequelize = require('sequelize');
var sequelize = new Sequelize('mydatabase', 'root', 'root', {
    host: 'localhost',
    dialect: 'mysql',
    port: 8889,

    pool: {
        max: 5,
        min: 0,
        idle: 10000
    },
    define: {
        timestamps: false
    }
});

var db = {};
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;

models.js

var db = require('./db'),
    sequelize = db.sequelize,
    Sequelize = db.Sequelize;

var feed = sequelize.define('feeds', {
    subscriber_id: Sequelize.INTEGER,
    activity_id: Sequelize.INTEGER
},
{
    tableName: 'feeds',
    freezeTableName: true
});

routes/index.js

var express = require('express');
var router = express.Router();
var models = require('../models');

router.get('/addfeed', function(req,res) {
    sequelize.sync().then(function () {
        return feed.create({
            subscriber_id: 5008,
            activity_id : 116
        });
    }).then(function (jane) {
        res.sendStatus(jane);
    });
});

Upvotes: 13

Views: 41099

Answers (5)

Abhishek
Abhishek

Reputation: 1130

I came with the same issue when I used something like:

const { Feed } = require("../models/Feed.js");

So, just using the code down below solved it

const { Feed } = require("../models");

Upvotes: 2

Muhammad Uzair
Muhammad Uzair

Reputation: 494

Update :

in newer version of sequelize v6 and beyond sequelize.import is deprecated

sequelize docs recommend using require now

If you have generated models using migrations

this is how your model file will look like

models/user.js

'use strict'
module.exports = (sequelize, DataTypes, Model) => {
    class User extends Model {
        /**
         * Helper method for defining associations.
         * This method is not a part of Sequelize lifecycle.
         * The `models/index` file will call this method automatically.
         */
        static associate(models) {
            // define association here
        }
    };
    User.init({
        name: {
            type: DataTypes.STRING,
            allowNull: false
        },
        phone_number: {
            type: DataTypes.STRING(20)
        },
        otp: {
            type: DataTypes.INTEGER(4).UNSIGNED
        },{
        sequelize,
        modelName: 'User',
    });
    return User;
};

as you can see your model export function has sequelize DataTypes & Model parameters.

so when you import this model you should send above arguments.

Example

I am importing user model in controllers/user.js file, it could be any file

controllers/controller.js

const Sequelize = require('sequelize');
const sequelize = require('../config/db').sequelize;

// Bring in Model
const User = require('../models/user')(sequelize, Sequelize.DataTypes,
     Sequelize.Model);
// your code...
// User.create(), User.find() whatever

Notice that sequelize(with small 's') and Sequelize(with capital 'S') are different things, first one represent instance of Sequelize created using new Sequelize, second one is just package you installed & imported

first one (sequelize) can be found wherever you started a connection to database using const sequelize = new Sequelize() usually from app.js or db.js file, make sure to export it from there and import it into where you want to use Model i.e controller

export sequelize instance

db.js Or app.js

const sequelize = new Sequelize();
... //your code
...
module.exports = {
sequelize: sequelize
}

Upvotes: 5

Brian Kariuki
Brian Kariuki

Reputation: 51

Just use

const { User } = require("../models");

Upvotes: 5

Micah Bala
Micah Bala

Reputation: 141

You may want to check the answer given on the link below tackling the same issue, I was able to resolve mine using const User = sequelize.import('../models/users');, instead of just import User from '../models/users';

Sequelize create not a function?

Upvotes: 0

0xmtn
0xmtn

Reputation: 2670

You cannot reach a variable from a file, by only requiring it in another one. You need to either define an object literal to hold all your variables in one place and assign it to module.exports, or you need to import them from different files separately.

In your case, I would create separate files to hold table schemas, and then import them by sequelize.import under one file, then require that file.

Like this:

models/index.js:

var sequelize = new Sequelize('DBNAME', 'root', 'root', { 
  host: "localhost",           
  dialect: 'sqlite',           

  pool:{
    max: 5, 
    min: 0,
    idle: 10000                
  },

  storage: "SOME_DB_PATH"
}); 

// load models                 
var models = [                 
  'Users',            
];
models.forEach(function(model) {
  module.exports[model] = sequelize.import(__dirname + '/' + model);
});

models/Users.js

var Sequelize = require("sequelize");

module.exports=function(sequelize, DataTypes){ 
  return Users = sequelize.define("Users", {
    id: {
      type: DataTypes.INTEGER, 
      field: "id",             
      autoIncrement: !0,       
      primaryKey: !0
    },
    firstName: {               
      type: DataTypes.STRING,  
      field: "first_name"      
    },
    lastName: {                
      type: DataTypes.STRING,  
      field: "last_name"       
    },
  }, {
    freezeTableName: true, // Model tableName will be the same as the model name
    classMethods:{

      }
    },
    instanceMethods:{

      }
    }
  });
};

Then import each model like this:

var Users = require("MODELS_FOLDER_PATH").Users;

Hope this helps.

Upvotes: 19

Related Questions