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