[英]Mongo node expressJs database connections
我正在使用帶有node
/ express
的mongoDB
數據庫,我想知道如何使它更簡潔。
app.get('/mediums', function(req, res){
db.open(function(err, db) {
db.collection('mediums').find().toArray(function(err, info){
res.json(info)
db.close();
})
});
});
app.get('/categories', function(req, res){
db.open(function(err, db) {
db.collection('categories').find().toArray(function(err, info){
res.json(info)
db.close();
})
});
});
app.get('/stock', function(req, res){
db.open(function(err, db) {
db.collection('stock').find().toArray(function(err, info){
res.json(info)
db.close();
})
});
});
我想一次編寫db.open
,然后在需要時調用它
更像
database = db.open(function(err, db) {
db.collection('stock').find().toArray(function(err, info){
callback()
db.close();
})
});
app.get('/stock', function(req, res){
database.collection('stocks').find().toArray(function(err, info ){
res.json(info)
})
});
我知道這不是有效的JS,但類似這樣的功能真棒!
通常,運行服務器時, mongoDB
連接將永遠保持打開狀態。 每次打開和關閉連接都是低效率且麻煩的。 啟動服務器時只需打開連接,然后在需要查詢數據庫的任何地方傳遞該變量。
你可以做這樣的事情
db.open(function(err, db) {
//start your express server here
//use the db to query in the routes.
//If you need the db in other files, you can use something like exports.db=db
//in the case db isn't a singleton.
})
您可以將應用程序初始化內容放入db.open
的回調中。 像這樣:
db.open(function(err, db) {
app.get('/mediums', function(req, res){
db.collection('mediums').find().toArray(function(err, info){
res.json(info);
});
});
app.get('/categories', function(req, res){
db.collection('categories').find().toArray(function(err, info){
res.json(info);
});
});
app.get('/stock', function(req, res){
db.collection('stock').find().toArray(function(err, info){
res.json(info);
});
});
});
您可能還希望在db.open
回調中進行.listen
調用,以使應用程序在打開數據庫連接之前不會開始監聽。
您可以嘗試這樣的事情:
app.js / server.js
...
let _db = null;
MongoClient.connect('mongodb://localhost/test', (err, db) => {
_db = db;
});
app.use(function(req, res, next) {
res.locals.db = _db;
next();
});
...
路線/mediums.js
...
router.get('/mediums', function(req, res) {
res.locals.db.collection('mediums').find().toArray(function(err, info){
res.json(info)
db.close();
});
});
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.