Sequelize Issue By Separating Model Logic from Model Configuration

六月ゝ 毕业季﹏ 提交于 2020-01-06 21:25:24

问题


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
    }));
});

回答1:


I think problem in your post method, but structure is really confusing so can you do this

models/index.js

"use strict";

var fs        = require("fs");
var path      = require("path");
var Sequelize = require("sequelize");
var env       = process.env.NODE_ENV || "development";
var config    = require(__dirname + '/../config/config.json')[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db        = {};

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf(".") !== 0) && (file !== "index.js");
  })
  .forEach(function(file) {
    var model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if ("associate" in db[modelName]) {
    db[modelName].associate(db);
  }
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

models/ann-model.js

"use strict";

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;
}

routes/index.js

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

appRoutes.route('/') 

    .get(function(req, res){
        res.send('ok');
    })

    .post(function(req, res){

      models.ann
      .build({ ann_id: 55, ann_date: new Date() })
      .save()
      .then(function(anotherTask) {
        res.send("POST OK"); 
      }).catch(function(error) {
        res.send(error);
      })

    });

module.exports = appRoutes;


来源:https://stackoverflow.com/questions/33977761/sequelize-issue-by-separating-model-logic-from-model-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!