Migrating from Sequelize to Objection
I did a bit of research when I first set up my project as to what ORM I was going to use. The reason I chose to use an ORM is because I’ve always had the option to do so (and I wouldn’t say my SQL is very strong). I ended up using Sequelize on this most recent project and keep finding it difficult to work with. So I decided it was time to make a change.
I looked around a bit and it seems like people are really liking Objection as an ORM option as it allows them to also use more raw SQL if need be.
Install objection and knex
The first thing to do is to install both objection and knex.
npm install objection knex
You then need to install the package for whatever database you plan on using (i.e. mysql, postgres)
In my instance, I’m using postgres.
npm install pg
Create migration file
Add a package.json script to run the migration file
"migrate": "npx knex migrate:latest --knexfile ./db/knexfile.js"
npm run migrate
This will create a migrations file where you can add your initial database info.
How to rollback migration
knex migrate:rollback
Create seed data
Add a script to make seed file
"seed-dev": "npx knex seed:make dev --knexfile ./db/knexfile.js"
npm run make-seed-dev
This creates a seed file we can use to add sample data to our database.
To run a seed file
"seed": "npx knex seed:run --knexfile ./db/knexfile.js"
Insert the seed data
npm run seed
If you have issues with directory structure not working for your seed, take a look at your knex config file. Make sure to adjust the
seeds: {
directory: './path-to-seeders-folder',
},
"migrate-down": "npx knex migrate:down --knexfile ./src/db/knexfile.js",
npm run migrate-down
Another problem you can run into is your knexfile not having access to your .env variables. My db configuration is nested in my src folder, requiring my dotenv declaration to specify my .env path.
import dotenv from 'dotenv';
dotenv.config({ path: 'path/to/your/env/file'});