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

前端 未结 11 2334
旧巷少年郎
旧巷少年郎 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
    
    0 讨论(0)
  • 2020-11-22 03:17

    Open a new connection when the Node.js application starts, and reuse the existing db connection object:

    /server.js

    import express from 'express';
    import Promise from 'bluebird';
    import logger from 'winston';
    import { MongoClient } from 'mongodb';
    import config from './config';
    import usersRestApi from './api/users';
    
    const app = express();
    
    app.use('/api/users', usersRestApi);
    
    app.get('/', (req, res) => {
      res.send('Hello World');
    });
    
    // Create a MongoDB connection pool and start the application
    // after the database connection is ready
    MongoClient.connect(config.database.url, { promiseLibrary: Promise }, (err, db) => {
      if (err) {
        logger.warn(`Failed to connect to the database. ${err.stack}`);
      }
      app.locals.db = db;
      app.listen(config.port, () => {
        logger.info(`Node.js app is listening at http://localhost:${config.port}`);
      });
    });
    

    /api/users.js

    import { Router } from 'express';
    import { ObjectID } from 'mongodb';
    
    const router = new Router();
    
    router.get('/:id', async (req, res, next) => {
      try {
        const db = req.app.locals.db;
        const id = new ObjectID(req.params.id);
        const user = await db.collection('user').findOne({ _id: id }, {
          email: 1,
          firstName: 1,
          lastName: 1
        });
    
        if (user) {
          user.id = req.params.id;
          res.send(user);
        } else {
          res.sendStatus(404);
        }
      } catch (err) {
        next(err);
      }
    });
    
    export default router;
    

    Source: How to Open Database Connections in a Node.js/Express App

    0 讨论(0)
  • 2020-11-22 03:23

    I have implemented below code in my project to implement connection pooling in my code so it will create a minimum connection in my project and reuse available connection

    /* Mongo.js*/
    
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/yourdatabasename"; 
    var assert = require('assert');
    
    var connection=[];
    // Create the database connection
    establishConnection = function(callback){
    
                    MongoClient.connect(url, { poolSize: 10 },function(err, db) {
                        assert.equal(null, err);
    
                            connection = db
                            if(typeof callback === 'function' && callback())
                                callback(connection)
    
                        }
    
                    )
    
    
    
    }
    
    function getconnection(){
        return connection
    }
    
    module.exports = {
    
        establishConnection:establishConnection,
        getconnection:getconnection
    }
    
    /*app.js*/
    // establish one connection with all other routes will use.
    var db = require('./routes/mongo')
    
    db.establishConnection();
    
    //you can also call with callback if you wanna create any collection at starting
    /*
    db.establishConnection(function(conn){
      conn.createCollection("collectionName", function(err, res) {
        if (err) throw err;
        console.log("Collection created!");
      });
    };
    */
    
    // anyother route.js
    
    var db = require('./mongo')
    
    router.get('/', function(req, res, next) {
        var connection = db.getconnection()
        res.send("Hello");
    
    });
    
    0 讨论(0)
  • 2020-11-22 03:23

    mongodb.com -> new project -> new cluster -> new collection -> connect -> IP address: 0.0.0.0/0 & db cred -> connect your application -> copy connection string and paste in .env file of your node app and make sure to replace "" with the actual password for the user and also replace "/test" with your db name

    create new file .env

    CONNECTIONSTRING=x --> const client = new MongoClient(CONNECTIONSTRING) 
    PORT=8080 
    JWTSECRET=mysuper456secret123phrase
    
    0 讨论(0)
  • 2020-11-22 03:24

    Best approach to implement connection pooling is you should create one global array variable which hold db name with connection object returned by MongoClient and then reuse that connection whenever you need to contact Database.

    1. In your Server.js define var global.dbconnections = [];

    2. Create a Service naming connectionService.js. It will have 2 methods getConnection and createConnection. So when user will call getConnection(), it will find detail in global connection variable and return connection details if already exists else it will call createConnection() and return connection Details.

    3. Call this service using db_name and it will return connection object if it already have else it will create new connection and return it to you.

    Hope it helps :)

    Here is the connectionService.js code:

    var mongo = require('mongoskin');
    var mongodb = require('mongodb');
    var Q = require('q');
    var service = {};
    service.getConnection = getConnection ;
    module.exports = service;
    
    function getConnection(appDB){
        var deferred = Q.defer();
        var connectionDetails=global.dbconnections.find(item=>item.appDB==appDB)
    
        if(connectionDetails){deferred.resolve(connectionDetails.connection);
        }else{createConnection(appDB).then(function(connectionDetails){
                deferred.resolve(connectionDetails);})
        }
        return deferred.promise;
    }
    
    function createConnection(appDB){
        var deferred = Q.defer();
        mongodb.MongoClient.connect(connectionServer + appDB, (err,database)=> 
        {
            if(err) deferred.reject(err.name + ': ' + err.message);
            global.dbconnections.push({appDB: appDB,  connection: database});
            deferred.resolve(database);
        })
         return deferred.promise;
    } 
    
    0 讨论(0)
提交回复
热议问题