Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
});
like image 247
salep Avatar asked Apr 21 '26 01:04

salep


1 Answers

If I understand correctly the directory structure of your project, you have the routes directory next to the models directory, right? if this is the case, you need to change the require in routes/index.js to use ../, so it will get to the right location:

var User = require('../models/User');
like image 182
Nir Levy Avatar answered Apr 23 '26 15:04

Nir Levy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!