I am following the sequelize best practices by connecting to a host and importing all models into one file and then calling that file when interacting the model. For some reason it looks like this is causing an issue as I am getting an error at using the define
method for the sequelize variable and I ran a test with a file that contained both logic together and I was able to add a user.
Error:
TypeError: Cannot read property 'define' of undefined at new module.exports (/Users/user/Desktop/Projects/node/ann/app/models/ann-model.js:3:27) at /Users/user/Desktop/Projects/node/ann/app/controllers/appRoutes.js:13:20
Here is my file that contains the connection to the database (dbIndex.js):
var Sequelize = require('sequelize'); var sequelize = new Sequelize('dbname', 'user', 'pwd', { host:'localhost', port:'3306', dialect: 'mysql' }); sequelize .authenticate() .then(function(err) { if (!!err) { console.log('Unable to connect to the database:', err) } else { console.log('Connection has been established successfully.') } }); var db = {} db.Ann = sequelize.import(__dirname + "/ann-model"); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
Here is the Model file (ann-model.js):
module.exports = function(sequelize, DataTypes) { var Ann = sequelize.define('ann', { ann_id: { type: DataTypes.INTEGER, primaryKey: true }, ann_date: DataTypes.DATE, }, { freezeTableName: true }); return Ann; }
Here is where I'm calling the model with a POST method.
(appRoutes.js):
var express = require('express'); var appRoutes = express.Router(); var Annotation = require('../models/ann-model'); appRoutes.route('/') .get(function(req, res){ res.render('pages/activity-feed.hbs'); }) .post(function(req, res){ var ann = new Ann(); ann.ann_date = req.body.ann-date; annotation.save(function(err){ if (err) res.send(err); }); }); module.exports = appRoutes;
Test file combining logic and modeling in one file:
var Sequelize = require('sequelize'); var sequelize = new Sequelize('dbname', 'user', 'pwd', { host:'localhost', port:'3306', dialect: 'mysql' }); var Ann = sequelize.define('ann', { ann_id: { type: Sequelize.INTEGER, primaryKey: true }, ann_date: Sequelize.DATE, }, { freezeTableName: true }); sequelize.sync().then(function(){ return Ann.create({ ann_id: 3, discovery: 'This is a test.' }); }).then(function(tation) { console.log(tation.get({ plain: true })); });