Search code examples
node.jsknex.js

Knex.js: Create table and insert data


Given that I have a Knex.js script like this:

exports.up = function(knex, Promise) {
    return knex.schema.createTable('persons', function(table) {
        table.increments('id').primary();
        table.string('name').notNullable();
    });
};

which currently creates a table.

How do I add subsequent insert statements to this script?

What I want to do is add a line like this (or similar):

knex.insert({id: 1, name: 'Test'}).into('persons')

I'm not sure I understand how this promise-based approach works. Am I supposed to write another script with insert statements? Or can I somehow append them to my existing script?

Unfortunately, I don't find any complete example of create + insert in Knex.js documentation.


Solution

  • The then method returns a Promise, which you can use to implement insertion after you have created the table. For example:

    exports.up = function (knex, Promise) {
        return Promise.all([
            knex.schema.createTableIfNotExists("payment_paypal_status", function (table) {
                table.increments(); // integer id
    
                // name
                table.string('name');
    
                //description
                table.string('description');
            }).then(function () {
                    return knex("payment_paypal_status").insert([
                        {name: "A", description: "A"},
                        {name: "B", description: "BB"},
                        {name: "C", description: "CCC"},
                        {name: "D", description: "DDDD"}
                    ]);
                }
            ),
        ]);
    };
    
    exports.down = function (knex, Promise) {
        return Promise.all([
            knex.schema.dropTableIfExists("payment_paypal_status")
        ]);
    };