Node.js and MongoDB, reusing the DB object

前端 未结 2 1219
温柔的废话
温柔的废话 2020-12-23 10:35

I\'m new to both Node.js and MongoDB, but I\'ve managed to put some parts together from SO and the documentation for mongo.

Mongo documentetion gives the example:

2条回答
  •  无人及你
    2020-12-23 11:22

    From your last code snippet, seems like you using Express or similar framework. You can use express-mongo-db to get connection inside req object. This middleware will cache connection for you and share it with other incoming requests:

    app.use(require('express-mongo-db')(require('mongodb'), { db: 'test' }))
    app.post('/employee', function(req, res){
        // req.db.collection('names'),insert(req.name)
        // Put req.name in database
    });
    
    
    app.post('/car', function(req, res){
        // req.db.collection('names').insert(req.name)
        // Put req.car in database
    });
    

提交回复
热议问题