简体   繁体   English

如何在 Nodejs 中重用 MongoDB 连接

[英]How can I reuse MongoDB connections in Nodejs

I am trying to reuse MongoDB Connections in NodeJS.我正在尝试在 NodeJS 中重用 MongoDB 连接。 I am using Native MongoDB Driver v3.6.6.我正在使用本机 MongoDB 驱动程序 v3.6.6。 I have read and used the code from this question , this question and many others like it.我已经阅读并使用了这个问题这个问题和许多其他喜欢它的代码。 My app.js is as follows:我的 app.js 如下:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
var mongoCon=require('./modules/mongoCon');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var config=require('./config.json');
var app = express();
mongoCon.connectDb(function(db){
  app.use(session({"secret": config["sessionSecret"]}));

  // view engine setup
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'ejs');

  app.use(logger('dev'));
  app.use(express.json());
  app.use(express.urlencoded({ extended: false }));
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, 'public')));

  app.use('/', indexRouter);
  app.use('/users', usersRouter);

  // catch 404 and forward to error handler
  app.use(function(req, res, next) {
    next(createError(404));
  });

  // error handler
  app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
  });
})
module.exports = app;

My mongoCon file is as follows:我的 mongoCon 文件如下:

const MongoClient = require( 'mongodb' ).MongoClient;
const mongoCredentials=require('./../config.json')["mongoCredentials"];
var url;
url = "mongodb://"+mongoCredentials["url"]+":"+mongoCredentials["port"];

var _db;
var client=new MongoClient(url,{ useNewUrlParser: true,useUnifiedTopology: true });

module.exports=
{
  connectDb: async function(func=null){
    await client.connect();
      this._db  = await client.db(mongoCredentials["db"]);
      console.log("Database Connected");
      if(func!=null){
        func(this._db)
      }
      return this._db;
  },
  getDb: async function(func=null){
    if(this._db){
      if(func!=null){
        func(this._db)
      }
      return this._db;
    }
    else{
      await this.connectDb();
      if(func!=null){
        func(this._db)
      }
      return this._db;
    }
  }
}

When I want to reuse the connections I call MongoCon.getDb().当我想重用连接时,我调用 MongoCon.getDb()。 But this opens a new db Connection instead of reusing it.但这会打开一个新的数据库连接而不是重用它。 If I remove the check for __db in getDb(), it returns undefined.如果我在 getDb() 中删除对 __db 的检查,它会返回未定义。 I am not sure how to solve this.我不知道如何解决这个问题。

Try to export connection instance only instead of connectDb and getDb, You can do something like this:尝试仅导出连接实例而不是 connectDb 和 getDb,您可以执行以下操作:

const { MongoClient } = require( 'mongodb' );
const client = new MongoClient(uri);

const DbConnection = () =>  {

    var db = null;
    var model = null;

    const getDBConnection = async () => {
        try {
            let url = 'mongodb://"+mongoCredentials["url"]+":"+mongoCredentials["port"';
            let db = await client.connect(url, {useNewUrlParser:true, useUnifiedTopology:true});
            return db
        } catch (e) {
            return e;
        }
    }

   const getInstance = async () => {
        try {
            if (db != null) {
                console.log(" db connection is already alive");
                return db;
            } else {
                console.log('getting new connection');
                db = await getDBConnection();
                return db;
            }
        } catch (e) {
            return e;
        }
    }

    return getInstance;
}

export default {db: DbConnection()}

In the files you import:在您导入的文件中:

const dbConnection = require('path to file');

const dbInstance =  async() => {
   const db = await dbConnection();
}

use mongoose and export connection from mongoose and shared between files使用 mongoose 并从 mongoose 导出连接并在文件之间共享

const mongoose = require("mongoose");
exports.isReady = false;
exports.connection = null;

mongoose.connect(config.mDB.serverUrl, { useFindAndModify: false, useUnifiedTopology: true, useNewUrlParser: true })
    .then(function (res) {
        
        // console.log('Succeeded connected to: ' + config.mDB.serverUrl);
        exports.isReady = true;
        exports.connection = res;
        exports.con = res.connection
    })

    .catch(function (err) {
       
        // console.error(err)
        // console.log('ERROR connecting to: ' + config.mDB.serverUrl, + '. ' + err);
    })

in another file import this as DB在另一个文件中将其导入为 DB

var DB = require('./DB')
DB.con.collection('test').findAll({}).toArray()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM