I\'m still not sure how to do my migrations with knex. Here is what I have so far. It works on up, but down gives me FK constraint error even though fo
I thought I'd update this, since there have been some additions to Javascript that make this quite a bit easier. knex still requires that you return a Promise but inside that Promise you can do a lot of things to clean up the code related to the creation/modification of tables. My preference is to use a combination of async/await and Promise.all.
exports.up = function(knex, Promise) {
return new Promise(async (resolve, reject) => {
try {
await Promise.all([
knex.schema.createTable('videos', table => {
table.increments('id');
table.string('title');
table.string('director');
table.json('meta');
}),
knex.schema.createTable('books', table => {
table.increments('id');
table.string('title');
table.string('author');
table.json('meta');
})
]);
console.log('Tables created successfully');
resolve();
} catch(error) {
reject(error);
}
})
}
If you prefer to create each table individually, then I'd just use async/await.
exports.up = function(knex, Promise) {
return new Promise(async (resolve, reject) => {
try {
await knex.schema.createTable('videos', table => {
table.increments('id');
table.string('title');
table.string('director');
table.json('meta');
});
console.log('videos table created successfully!');
await knex.schema.createTable('books', table => {
table.increments('id');
table.string('title');
table.string('author');
table.json('meta');
});
console.log('books table created successfully!');
resolve();
} catch(error){
reject(error);
}
})
}
This keeps things a lot cleaner, not requiring you to daisy chain a bunch of thens or wrap them in surrounding functions. You just await for each table creation to resolve and then resolve their encapsulating Promise! Yay for async/await!
You can follow this pattern for the dropping of tables in your down migration, too. Simply replace the knex.schema.createTable statements with knex.schema.dropTable statements.