Lola
Lola

Reputation: 145

Sequelize sync() doesn't create all of the table models

I'm quite new to using sequelize and node.js.

I'm trying to create two tables under models 'user' and 'post' using sequelize, postgres and node.js. The problem is, that only the 'posts' table is being created while the 'users' isn't created at all.

this is the code for 4 of the files: 'models/post' , 'models/user', 'app.js' and 'utils/database' :

'models/post':

const Sequelize = require('sequelize');

const sequelize = require('../util/database');

const Post = sequelize.define('post',{
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true,
    },
    title:{ 
        type: Sequelize.STRING,
        allowNull: false,
    },
    content:{ 
        type: Sequelize.STRING,
        allowNull: false,
    },
    tags:{
        type: Sequelize.ARRAY(Sequelize.STRING),
        allowNull: false,
    }

});

Post.associate = (models) => {
    Post.belongsTo(models.User, {
        constraints: true, 
        onDelete: 'CASCADE'
    });
}

module.exports = Post;

'models/user':


const sequelize = require('../util/database');

const User = sequelize.define('user', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true,
    },
    userName: {
        type: Sequelize.STRING,
        allowNull: false,
    },
    firstName: {
        type: Sequelize.STRING,
        allowNull: false,
    },
    lastName: {
        type: Sequelize.STRING,
        allowNull: false,
    },
    bio: {
        type: Sequelize.STRING,
        allowNull: false,
    },
    password: {
        type: Sequelize.STRING,
        allowNull: false,
    }
})

User.associate = (models) => {
    User.hasMany(models.Post);
}

module.exports = User;

'app.js':

const express = require('express');
const bodyParser = require('body-parser');
const graphqlHttp = require('express-graphql');

const sequelize = require('./util/database');
const graphqlSchema = require('./graphql/schema');
const graphqlResolver = require('./graphql/resolvers');

app = express();

app.use(bodyParser.json()); 
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader(
      'Access-Control-Allow-Methods',
      'OPTIONS, GET, POST, PUT, PATCH, DELETE'
    );
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
  });

app.use('/graphql', graphqlHttp({
    schema: graphqlSchema,
    rootValue: graphqlResolver,
    graphiql: true,
    formatError(err) {
      if (!err.originalError) {
        return err;
      }
      const data = err.originalError.data;
      const message = err.message || 'An error occurred.';
      const code = err.originalError.code || 500;
      return { message: message, status: code, data: data };
    }
  })
);

app.use((error, req, res, next) => {
  const status = error.statusCode || 500;
  const message = error.message;
  const data = error.data;
  res.status(status).json({ message: message, data: data });
});

 sequelize.sync({force: true})
  .then(result => {
    app.listen(8080);
  })
  .catch(err => {
    console.log(err);
  });

'utils/database':

const Sequelize = require('sequelize').Sequelize;

const sequelize = new Sequelize('projectname','postgres','password',{
    host: 'localhost',
    dialect: 'postgres', 

});

module.exports = sequelize;

(projectname and password are of-course replaced with the true values)

Upvotes: 0

Views: 6285

Answers (1)

Anatoly
Anatoly

Reputation: 22758

  1. Register your models and their associations in utils/database
  2. Move sync call before registering any routes

utils/database

const sequelize = new Sequelize('projectname','postgres','password',{
    host: 'localhost',
    dialect: 'postgres', 

});

const db = {}
const models = path.join(__dirname, 'models') // path to a models' folder

fs.readdirSync(models)
  .filter(function (file) {
    return (file.indexOf('.') !== 0)  && (file.slice(-3) === '.js')
  })
  .forEach(function (file) {
    var model = sequelize['import'](path.join(models, file))
    db[model.name] = model
  })

Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db)
  }
})

module.exports = sequelize

Upvotes: 1

Related Questions