smoczyna
smoczyna

Reputation: 519

NodeJS and Knex - tables are not created automatically

I have NodeJS application base on SQLite. My problem is that DB is not being initialized on startup. No tables are created but my queries run fine (with no such table error). Here is my config.js contents. This file is called whenever database is neeeded.

var knex = require('knex')({
    client: 'sqlite3',
    connection: {
        filename: "db.sqlite"
    },
    useNullAsDefault: true
});

//var bookshelf = require('bookshelf')(knex);
//bookshelf.plugin('registry');

module.exports = {
    "port": process.env.PORT || 3000,
    "secretKey": "MyOwnSecretKey",
    "knex": knex
    //"bookshelf": bookshelf
};

Now in my user.js file I am calling this with the following:

var config = require('../../config');
var bcrypt = require('bcrypt-nodejs');

var knex = config.knex;
knex.schema.createTableIfNotExists('users', function(table) {
    table.increments();
    table.string('name', 128);
    table.string('username', 128);
    table.string('password');
    //table.string('email', 128);
    //table.string('role').defaultTo('admin');    
    table.timestamps();
});

//var bookshelf = config.bookshelf;
var bookshelf = require('bookshelf')(knex);
bookshelf.plugin('registry');

var User = bookshelf.Model.extend({
    tableName: 'users',
    ...

when I try to call any method getting or creating data I have error that the table does not exist. I have moved table creation part to my server.js file too but it also didn't create the table (although debugging show that it should). What is the catch here? Or perhaps there is a better way to create tables that this?

Upvotes: 2

Views: 2617

Answers (1)

Ram
Ram

Reputation: 144699

knex has weird APIs. The query is not executed unless you call the then method which can be considered as an exec method. So try calling the then method on the migration query.

Note that the API is async and you should wait until the tables are created before querying the tables. You shouldn't put your migration code in your model files after all. knex has a CLI for generating and executing migration files!

Create a folder for database migrations and then use the $ knex migrate:make file_name_goes here command for creating a migration file. Then you can use the $ knex migrate:latest command for executing the migration files.

Upvotes: 1

Related Questions