Michael Michael - 25 days ago 9
MySQL Question

Accessing orm data in a node express post callback

I try to set up a JSON API with Express 4.14.0 (orm 3.1.0 / mySQL) In the app.js I have:

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var data = require('./model/datamodel');
var api = require('./routes/api');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', api);

module.exports = app;


I use datamodel.js for setting up the orm:

var express = require('express');
var orm = require('orm');
var app = express();

app.use(orm.express("mysql://onserver:>2hZ[RpfCT~!xx@localhost/onserver", {
define: function (db, models, next) {
models.person = db.define("person", {
name : String,
surname : String,
} );

next();
}
}));


And api.js for the actual api:

var express = require('express');
var router = express.Router();
var app = express();

router.get('/', function(req, res, next) {
res.json({ message: 'hoorayDATABASE: undefined! welcome to our api!' });
});

router.route( "/main" ).post( function( req, res ) {
console.log( "MODELS:", req.models );
// req.models is undefined
// I want to access req.models.person.find( ... )
})

module.exports = router;


I call
localhost:3000/main
and I receive:


MODELS: undefined


I need the models object to retrieve the data, but it is undefined. Why?

Answer

You're defining new app in datamodel.js. You only need to do var app = express(); once in your application and pass the app variable to other modules so that they all refer to the same instance.

This is how it can be done:

app.js

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

// require the module and pass the `app` to the function it exports
require('./model/datamodel')(app);

app.use('/', require('./routes/api'));

module.exports = app; 

datamodel.js

var orm = require('orm');

module.exports = function(app) {
    app.use(orm.express("mysql://onserver:>2hZ[RpfCT~!xx@localhost/onserver", {
        define: function (db, models, next) {
            models.person = db.define("person", { 
                name      : String,
                surname   : String,
            } );

            next();
        }   
    }));
}

api.js

var express = require('express');
var router = express.Router(); 

router.get('/', function(req, res, next) {
    res.json({ message: 'hoorayDATABASE: undefined! welcome to our api!' });  
});

router.post('/main', function( req, res ) { 
    console.log( "MODELS:", req.models );
})

module.exports = router;