Search code examples
mysqlnode.jsexpress-4

Express insert values into MySQL database


PROBLEM SOLVED. Please look below.

I'm new into Express and NodeJS, ditched Laravel and PHP.

What I want to do is to be able to add a record into MySQL database, but I am not able to connect the dots. I'm following this tutorial series :

http://eddyjs.com/bookshelf-js/

http://eddyjs.com/using-mysql-with-bookshelf-js-part-2-using-the-database/

There are two db variables, I couldn't understand how to use them.

Here's the error.

Cannot read property 'extend' of undefined

TypeError: Cannot read property 'extend' of undefined at Object. (/Applications/MAMP/htdocs/myapp/myapp/models/User.js:5:20) at Module._compile (module.js:460:26) at Object.Module._extensions..js (module.js:478:10) at Module.load (module.js:355:32) at Function.Module._load (module.js:310:12) at Module.require (module.js:365:17) at require (module.js:384:17)

I installed all dependencies via npm, everything is ok.

  "dependencies": {
    "body-parser": "~1.13.2",
    "bookshelf": "^0.8.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "jquery": "^2.1.4",
    "knex": "^0.8.6",
    "morgan": "~1.6.1",
    "mysql": "^2.9.0",
    "serve-favicon": "~2.3.0"
  }

I hold my models in models folder.

User.js

var db = require('./db');

var User = db.Model.extend({
    tableName: 'users'
});

module.exports = User;

routes/index.js

router.get('/add', function(req,res,next) {
  var User = require('../models/User');
  new User({
    'name': 'Edwin',
    'pet': 'dog'
  })
      .save()
      .then(function (newUser) {
        console.log('user created!', newUser);
      });
});

db.js (database connection should be opened once, right? So it has to live here)

   var knex = require('knex')({
    client: 'mysql',
    connection: {
        host     : 'localhost',
        user     : 'root',
        password : 'root',
        port    : 8889,
        database : 'databasename',
        charset  : 'utf8'
    }
});

var bookshelf = require('bookshelf')(knex);

var User = bookshelf.Model.extend({
  tableName: 'users'
});

Solution

  • Problem solved when I change db.js. The key is the module.exports = db; part, I guess.

    var knex = require('knex')({
        client: 'mysql',
        connection: {
            host     : 'localhost',
            user     : 'root',
            password : 'root',
            port    : 8889,
            database : 'bosluk',
            charset  : 'utf8'
        }
    });
    
    var db = require('bookshelf')(knex);
    
    module.exports = db;