访问节点中的orm数据表示回调后

时间:2016-11-15 12:31:39

标签: mysql node.js express orm routes

我尝试使用Express 4.14.0(orm 3.1.0 / mySQL)设置JSON API在app.js中我有:

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;                

我使用datamodel.js来设置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();
    }   
}));

和实际api的api.js:

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;  

我致电localhost:3000/main并收到:

  

MODELS:undefined

我需要models对象来检索数据,但它是未定义的。为什么呢?

1 个答案:

答案 0 :(得分:2)

您正在datamodel.js中定义新应用。您只需在应用程序中执行var app = express();一次,并将app变量传递给其他模块,以便它们都引用同一个实例。

这是如何做到的:

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;