2017-01-22 57 views
2

我在嘗試訪問在MongoDB客戶端模塊連接到我的MongoDB數據庫時創建的「DB」數據庫對象時遇到問題。將MongoDB對象數據庫傳遞到Express Middleware

此刻我收到一個錯誤,指出在data.js中'db'沒有被定義。我明白爲什麼這是 - 數據庫對象沒有被「傳遞」到路由器,然後通過控制器。

這樣做的最好方法是什麼?

我試圖將「db」對象傳遞給路由器(dataRoutes.js),但我無法確定如何使控制器(data.js)可以訪問此對象。有人可以幫忙嗎?

請注意我沒有包含其他路線和控制器,但他們只是通過POST方法提交表單到/ data/submit。下面的控制器旨在將此表單數據寫入MongoDB數據庫。

下面是相關代碼:

app.js

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

var routes = require('./routes/index'); 
var dataRoutes = require('./routes/dataRoutes'); 

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

// view engine setup 
app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'pug'); 


MongoClient.connect("mongodb://localhost:27017/m101", function(err, db) { 

    if(err) throw err; 

    console.log("Successfully connected to MongoDB."); 

    app.use('/', routes); // Use normal routes for wesbite 
    app.use('/data', dataRoutes); 


    app.get('/favicon.ico', function(req, res) { 
     res.send(204); 
    }); 

    app.use(function(req, res, next) { 
     var err = new Error('Oops Page/Resource Not Found!'); 
     err.status = 404; 
     next(err); //Proceed to next middleware 
    }); 

    if (app.get('env') === 'development') { 
     app.use(function(err, req, res, next) { 
// update the error responce, either with the error status 
// or if that is falsey use error code 500 
     res.status(err.status || 500); 
     res.render('error', { 
      message: err.message, 
      error: err 
     }); 
     }); 
    } 

    app.use(function(err, req, res, next) { 
     console.log('Error'); 
     res.status(err.status || 500); 
     res.render('error', { 
      message: err.message, 
      error: {} 
     }); 

    }); 

    var server = app.listen(3000, function() { 
     var port = server.address().port; 
     console.log("Express server listening on port %s.", port); 
    }); 

}); 

dataRoutes.js

// router 

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

    // controller references 
    var ctrlsData = require('../controllers/data'); 

    router.post('/submit', ctrlsData.submit); 


    module.exports = router; 

data.js

var MongoClient = require('mongodb').MongoClient; 

var sendJsonResponse = function(res, status, content) { 
    res.status(status); 
    res.json(content); 
}; 

module.exports.submit = function(req, res) { 
    var title = req.body.title; 
    var year = req.body.year; 
    var imdb = req.body.imdb; 

    /* 
    console.log('submitted'); 
    console.log(req.body); 
    sendJsonResponse(res, 201, {title,year,imdb}); 
    */ 

    var title = req.body.title; 
    var year = req.body.year; 
    var imdb = req.body.imdb; 



    if ((title == '') || (year == '') || (imdb == '')) { 
    sendJsonResponse(res, 404, { 
     "message": "Title, Year and IMDB Reference are all required." 
    }); 
    } else { 
     db.collection('movies').insertOne(
      { 'title': title, 'year': year, 'imdb': imdb }, 
      function (err, r) { 
      if (err) { 
       sendJsonResponse(res, 400, err); 
      } else { 
       sendJsonResponse(res, 201, "Document inserted with _id: " + r.insertedId + {title,year,imdb}); 
      } 
      } 
     ); 

    } 

}; 

回答

5

創建db變量參照的文CE的MongoDB在app.js

MongoClient.connect("mongodb://localhost:27017/m101", function(err, db) { 

    app.db = db; 

    //..... 
}); 

在​​,訪問dbreq.app

module.exports.submit = function(req, res) { 

    req.app.db.collection('movies').insertOne({ 'title': title, 'year': year, 'imdb': imdb }, 
     function(err, r) {} 
    ) 
}; 
+0

謝謝 - 偉大的答案! – Ctrp

相關問題