How do I manage MongoDB connections in a Node.js web application?

前端 未结 11 2338
旧巷少年郎
旧巷少年郎 2020-11-22 02:42

I\'m using the node-mongodb-native driver with MongoDB to write a website.

I have some questions about how to manage connections:

  1. Is it enough using

11条回答
  •  误落风尘
    2020-11-22 02:58

    If using express there is another more straightforward method, which is to utilise Express's built in feature to share data between routes and modules within your app. There is an object called app.locals. We can attach properties to it and access it from inside our routes. To use it, instantiate your mongo connection in your app.js file.

    var app = express();
    
    MongoClient.connect('mongodb://localhost:27017/')
    .then(client =>{
      const db = client.db('your-db');
      const collection = db.collection('your-collection');
      app.locals.collection = collection;
    });
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    

    This database connection, or indeed any other data you wish to share around the modules of you app can now be accessed within your routes with req.app.locals as below without the need for creating and requiring additional modules.

    app.get('/', (req, res) => {
      const collection = req.app.locals.collection;
      collection.find({}).toArray()
      .then(response => res.status(200).json(response))
      .catch(error => console.error(error));
    });
    

    This method ensures that you have a database connection open for the duration of your app unless you choose to close it at any time. It's easily accessible with req.app.locals.your-collection and doesn't require creation of any additional modules.

提交回复
热议问题