Reputation: 1749
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
Upvotes: 8
Views: 24195
Reputation: 2206
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.
Upvotes: 24