Sequelize.create is not an error function

I get an Unhandled rejection TypeError: feed.create is not a function error, and I cannot understand why this is happening. What is the problem?

Here is my code. I probably am not doing anything very fundamental here, since I cannot achieve the feed variable in the /index.js routes.

If I add module.exports = feed; to my model file, I can achieve this, but I have several models, so if I add additional models under 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); }); }); 
+6
source share
1 answer

You cannot get a variable from a file by only requiring it in another. You need to either define an object literal to store 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 for storing tabular schemas, and then import them under sequelize.import under one file, and then require this 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 as follows:

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

Hope this helps.

+11
source

All Articles