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
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With