如何访问从app.js到模型节点js的express-myconnection数据库连接

时间:2019-01-17 05:53:57

标签: node.js

我已经在app.js中定义了express-myconnection数据库连接,现在我想在task.js之类的模型中使用该数据库连接,如何在模型中也实现该连接。请给我更好的选择。

app.js

var createError = require('http-errors');
var express = require('express');
var session = require('express-session');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
// var passport = require('passport');
var cors=require('cors');
var flash = require('connect-flash');
var mysql = require('mysql');
// require('./config/passport')(passport);

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var Tasks=require('./routes/Tasks');
var app = express();
var customers = require('./routes/customers'); 
var login = require('./routes/login'); 
var connection  = require('express-myconnection');
// view engine setup
// app.set('port', process.env.PORT || 4300);
app.engine('pug', require('pug').__express);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// app.use(passport.initialize());
app.use(session({
 secret: 'justasecret',
 resave:true,
 cookie: {
      httpOnly: true,
      maxAge : 10000,
  },
 saveUninitialized: true
}));
/*------------------------------------------
    connection peer, register as middleware
    type koneksi : single,pool and request 
-------------------------------------------*/
// app.use(

//     connection(mysql,{

//         host: 'localhost',
//         user: 'root',
//         password : '',
//         port : 3306, //port mysql
//         database:'nodejs'
//     },'pool')
// );//route index, hello world
dbOptions = {
      host: 'localhost',
      user: 'root',
      password: '',
      port: 3307,
      database: 'nodejs'
    };
// const db = mysql.createPool(dbOptions); 
app.use(connection(mysql, dbOptions, 'pool'));
app.use(cors());
app.use(logger('dev'));
// app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(flash());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/customers', customers);
app.use('/admin',login);
app.use('/tasks',Tasks);
// require('./routes/login.js')(app, passport);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

inside models/tasks.js=>
var Task={

getAllTasks:function(callback){

return db.query("Select * from task",callback);

},
 getTaskById:function(id,callback){

return db.query("select * from task where Id=?",[id],callback);
 },
 addTask:function(Task,callback){
 return db.query("Insert into task values(?,?,?)",[Task.Id,Task.Title,Task.Status],callback);
 },
 deleteTask:function(id,callback){
  return db.query("delete from task where Id=?",[id],callback);
 },
 updateTask:function(id,Task,callback){
  return db.query("update task set Title=?,Status=? where Id=?",[Task.Title,Task.Status,id],callback);
 }

};

module.exports=Task;

1 个答案:

答案 0 :(得分:0)

express-myconnection 使用getConection(callback)函数扩展请求对象,这样,在请求/响应生命周期中,可以在路由器中的任何位置访问连接实例:

// myroute.js
...
module.exports = function(req, res, next) {
    ...
    req.getConnection(function(err, connection) {
      if (err) return next(err);

      connection.query('SELECT 1 AS RESULT', [], function(err, results) {
        if (err) return next(err);

        results[0].RESULT;
        // -> 1

        res.send(200);
      });

    });
    ...
}
...