How to Create a table in Sequelize to store in Postgressql with NodeJS
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.
Kannan T
Am a self-taught, programmer I code on Javascript love to build web applications. Interested in CP as well for that learning DS and Algo.
Updated on September 22, 2020Comments
-
Kannan T over 3 years
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
-
Kannan T over 6 years
News.sync({force: false}).then(function (err) { if(err) { console.log('An error occur while creating table'); } else{ console.log('Item table created successfully'); } });
-
Kannan T over 6 yearsThe above comment is the one am trying to do in console it prints An error occured while creating table however the table gets created and i can insert the values too. And by the way can you give me an simple example of that migrations API
-
Kannan T over 6 yearsIt doesn't print out any error it consoles the table name "user"
-
Zeke Nierenberg over 6 yearsAh, I see.
.then
does not report errors. Param one of.then
is the success result. to look for errors use.catch
-
Kannan T over 6 yearsUsed catch no errors printed thanks for helping me out bro am newbie to sequelize want to explore more so can you suggest me the resources for the same
-
Kannan T over 6 years
-
Kannan T over 6 yearscan you answer that question ?