Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create a table in Sequelize to store in Postgressql with NodeJS

Am a newbie to Postgres and Sequelize i have successfully connected to DB trying to create a table in DB that is where am struck am getting an error the tablename doesn't exist

sequelize.authenticate().then(() => {
  console.log("Success!");
  var News = sequelize.define('likes', {
    title: {
      type: Sequelize.STRING
    },
    content: {
      type: Sequelize.STRING
    }
    }, {
     freezeTableName: true
   });
   News.create({
     title: 'Getting Started with PostgreSQL and Sequelize',
     content: 'Hello there'
   });
   News.findAll({}).then((data) => {
     console.log(data);
   }).catch((err) => {
     console.log(err);
   });
}).catch((err) => {
  console.log(err);
}); 

Where am making a mistake? It says error: relation "likes" doesn't exist. Any kind of help is appreciated

like image 921
Kannan T Avatar asked Sep 21 '17 10:09

Kannan T


People also ask

How do I create a Sequelize table?

Sequelize create table with sync() method. The Sequelize model you create using the sequelize. define() method comes with a sync() method that you can use to create a table. The table created using the sync() method will follow the model definition for its column(s).

How do I insert a table into a Sequelize?

The create() method is used to insert a single row into your SQL table. When you need to insert multiple rows at once, you need to use the bulkCreate() method instead. Finally, you can also write and execute a raw SQL statement using the sequelize. raw() method.


1 Answers

Sequelize only creates tables through sync or migrations. Your model, News has a sync method, that when called will do one of a few things

If called with no params, it will create the table if it doesn't exist

if called like this News.sync({ force: true }) it will drop the current table if it exists and make a new one.

if called like this News.sync({ alter: true }) it will add any new fields that are not in the model yet (this is a v4 feature).

These techniques can be useful when rapidly prototyping, but the best solution is to use migrations. Migrations allow you to keep track of changes to your database across development, different git branches, and production. Its by far the best solution, but does come with a small amount of upfront cost and buy-in.

If you're working on a hackathon style project, I'd just go with {alter: true}, but if you're building something you're going to be working on for a while, definitely get to know the migrations API.

like image 147
Zeke Nierenberg Avatar answered Sep 19 '22 11:09

Zeke Nierenberg