In my express application I use Sequelize to manage the database. Here's my bootstrap code.
db.sequelize
.sync({ force: true})
.complete(function(err) {
if (err) {
throw err[0];
} else {
//seed
require('../db/seed')(db);
app.listen(app.get('port'), function() {
console.log('express listening on ' + app.get('port'));
});
}
});
As you can see, everytime I start the server first I seed the database with hard coded data.
Here's the code to initialize sequelize:
if (process.env.NODE_ENV === 'test') {
console.log('[test] using in memory database');
sequelize = new Sequelize('marbles-site-db', null, null, {
dialect: 'sqlite',
storage: ':memory:'
});
} else if (process.env.HEROKU_POSTGRESQL_WHITE_URL) {
var match = process.env.HEROKU_POSTGRESQL_WHITE_URL
.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/);
sequelize = new Sequelize(match[5], match[1], match[2], {
dialect: 'postgres',
protocol: 'postgres',
port: match[4],
host: match[3],
logging: true // false
});
} else {
sequelize = new Sequelize('marbles-site-db', null, null, {
dialect: 'sqlite',
storage: './db/development.sqlite'
});
}
As you can see, I use SQlite with flat file as storage for development and Postgres for production.
The problem is each time I restart the server, data in the database are gone. This is the case with SQlite, I suppose it's the same with Postgres too.
So what do I have to do to keep the data in the database even though I restart the server, and is this related to database migrations?
Note that the seed should not be needed after the initial boot.
sync({ force: true }) is mostly meant for testing, both user testing and testing internally in sequelize.
sync() does CREATE TABLE IF NOT EXISTS, so it can in theory be used in a production setting, since it will never destroy any existing data. However, if you change your schema in models, that will not be reflected in the DB if you only do sync
So, in a production setting you will need migrations. This means you both need to change your sequelize models, and write a migration each time you chnage something. There is talks about being able to automagically create migrations when the sequelize model file changes #120 but no work has been done on that yet