Mongo节点expressJs数据库连接

时间:2014-08-01 17:54:39

标签: node.js mongodb express

我正在使用mongoDB / node express数据库,我想知道如何让这更简洁。

    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,但这样的事情会很棒!

3 个答案:

答案 0 :(得分:1)

通常,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.

})

答案 1 :(得分:1)

您可以将应用初始化内容放在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);
        });
    });
});

您可能还希望在.listen回调中进行db.open调用,以便在数据库连接打开之前应用程序不会开始侦听。

答案 2 :(得分:0)

您可以尝试这样的事情:

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();
    });
});
...
相关问题