Search code examples
javascriptnode.jsbookshelf.jsknex.js

Why does insert script with Bookshelf.js hang?


I am a bit confused why the Node.js script does not exit:

// myscript.js
var Model = bookshelf.Model.extend({
  tableName: 'models'
});
var m = Model.forge({name: 'hello'});
m.save();
console.log("End");

But when running this with node myscript the script does not exit.

  • What is preventing the script from exiting?
  • How to cleanly exit after the model is saved?

Thanks!


Solution

  • What is preventing the script from exiting?

    Knex holds a pool of connections to your database. Although your script's execution ends, behind the scenes Knex is still maintaining these, preventing the program from closing.

    How to cleanly exit after the model is saved?

    You can tear down all the database connections by calling knex.destroy(). You must do this after your queries are complete.

    // myscript.js
    var Model = bookshelf.Model.extend({
      tableName: 'models'
    });
    
    Model.forge({name: 'hello'}).save().then(function(model) {
    
      console.log('model has been saved', model);
    
    }).catch(function(error) {
    
      // it's bad practise to omit some sort of error reporting.
      console.error('something went wrong!');
    
    }).finally(function() {
    
      // tear down connection.
      return bookshelf.knex.destroy();
    
    }).then(function () {
    
      // This is the actual 'end' of the program.
      console.log("End");
    
    });