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

前端 未结 11 2529
旧巷少年郎
旧巷少年郎 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 03:15

    You should create a connection as service then reuse it when need.

    // db.service.js
    import { MongoClient } from "mongodb";
    import database from "../config/database";
    
    const dbService = {
      db: undefined,
      connect: callback => {
        MongoClient.connect(database.uri, function(err, data) {
          if (err) {
            MongoClient.close();
            callback(err);
          }
          dbService.db = data;
          console.log("Connected to database");
          callback(null);
        });
      }
    };
    
    export default dbService;
    

    my App.js sample

    // App Start
    dbService.connect(err => {
      if (err) {
        console.log("Error: ", err);
        process.exit(1);
      }
    
      server.listen(config.port, () => {
        console.log(`Api runnning at ${config.port}`);
      });
    });
    

    and use it wherever you want with

    import dbService from "db.service.js"
    const db = dbService.db
    

提交回复
热议问题