1

I created an Ionic app and have the front-end working. Now I'm focusing on the backend using Node and Sequelize for my PostgreSQL db connection.

I created the connection in bin/www and am trying to use it in my models/user.js file (to create a user model), and in one of my route files (index.js) to try to create a new user and add it to the db.

I haven't used Sequelize before, so I'm not sure if I have the organizational flow right or not. I'm trying to use module.exports to pass the connection from one file to another, but it's actually passing undefined.

"GET /api/home 500 7.717 ms - 2567 TypeError: Cannot read property 'sync' of undefined
        at /Users/me/app/server/routes/api/index.js:13:12"

Is there a better way to do this?

This is the bin/www file:

var pg = require('pg');
var Sequelize = require("sequelize");

//DB CONNECTION
var sequelize = new Sequelize('dbname', 'postgres', 'password', {
  host: 'localhost',
  port: '5434',
  dialect: 'postgres',
  pool: {
    max: 5,
    min: 0,
    idle: 10000
  },
});

sequelize.authenticate().then(function(err) {
    if (err) console.log('Unable to connect to the PostgreSQL database:', err);
    console.log('Connection has been established successfully.');
});

module.exports.sequelize = sequelize;

This is my models/user.js:

var Sequelize = require("sequelize");
var sequelize = require("../bin/www").sequelize;

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('user', {
    fb_access_token: {
      type: Sequelize.STRING
    },
    fb_id: {
      type: Sequelize.STRING
    },
    book_wishlist: {
      type: Sequelize.ARRAY
    }
  }, {
    freezeTableName: true
  });
  return User;
}

And this is the index.js route:

var Sequelize = require("sequelize");
var express = require('express');
var router = express.Router();
var sequelize = require("../../../bin/www").sequelize;
var User = require('../../../models/user');

router.get('/home', function(req, res, next) {
  console.log('in router.get to home');
  console.log('User:',User);

  sequelize.sync({ force: true }).success(function(err) {
    //insert new user
    User.create({
      fb_access_token: "yes",
      fb_id: "no",
      book_wishlist: ["yes", "no"]
    }).success(function(user) {
      //you can now access the newly created user via the variable user
      console.log(user);
      res.send(user);
    });
  });
});
snwflk
  • 3,341
  • 4
  • 25
  • 37
mdegges
  • 963
  • 3
  • 18
  • 39
  • In index.js, could you do ```var sequelize = require("../../../bin/www"); console.log(sequelize)``` And paste the output – Yuri Zarubin Mar 25 '16 at 05:35
  • ahh yes- It returns an empty object: {} – mdegges Mar 25 '16 at 06:12
  • Ok, so you're doing everything correctly from a code perspective, but you have a tricky bug. It almost looks like you're loading a different file. What is `bin/www`? Is that a directory? Or is that literally `www.js`? – Yuri Zarubin Mar 25 '16 at 06:17
  • thanks for your help! bin is a directory with file www (an executable) inside of it. I've used it in most of my projects since it's included in the express generator- I usually put my mongoose connection in there and create my server. here I'm doing the same thing but with sequelize – mdegges Mar 25 '16 at 06:27
  • Is there a file called 'index.js' that directory? If so, what are its contents? – Yuri Zarubin Mar 25 '16 at 06:32
  • Also, is there anything else inside `bin/www.js`? Like, are you exporting anything else out of it? – Yuri Zarubin Mar 25 '16 at 06:34
  • there's nothing else in the bin directory except the www file. The index.js route I posted is in server/routes/api/index.js - a competely different directory – mdegges Mar 25 '16 at 06:41
  • At the end of `bin/www`, put `console.log(module.exports)`, and then run your server like usual. Does it print anything? – Yuri Zarubin Mar 25 '16 at 07:04
  • yep, it does! sequelize is in there as an object, with all of it's dependencies- options, config, dialect, etc – mdegges Mar 25 '16 at 07:15
  • the problem must be with the way I'm requiring it in – mdegges Mar 25 '16 at 07:17
  • @YuriZarubin thanks again for your help- I was able to get it working just by moving my db code to another file (not bin/www) – mdegges Mar 25 '16 at 17:59

1 Answers1

1

Finally figured this out thanks to Sean's answer in this Stackoverflow question - I created a new file in bin for my database connection (db.js) and exported sequelize doing module.exports = sequelize; I was then able to require it in doing var sequelize = require('../../../bin/db');

I'm still not sure why my earlier approach didn't work- the export from bin/www returned an empty object when I required it in in my other files. I think it has something to do with async behavior, as bin/www is called when I start nodemon.

Feel free to comment if you have any ideas.

Community
  • 1
  • 1
mdegges
  • 963
  • 3
  • 18
  • 39