当前位置: 首页 > 知识库问答 >
问题:

在NodeJS应用程序中实现singleton mongDB对象[duplicate]

齐起运
2023-03-14

目前正在nodeJS中开发一个后端,它使用expresssocket.io,并将MongoDB作为其数据库。我读到实现单例DB连接是一个很好的实践,它将在整个应用程序中重用。我试图实现这个还没有找到解决方案。我试图使用go-oleg的这个SO答案。

我复制了第一部分,外部mongoUtil.js文件如下:

var MongoClient = require( 'mongodb' ).MongoClient;

var _db;

module.exports = {

  connectToServer: function( callback ) {
    MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db ) {
      _db = db;
      return callback( err );
    } );
  },

  getDb: function() {
    return _db;
  }
};

然后在我的server.js我像这样调用这个函数一次(我不做任何回调,这是必需的吗?)。

var mongoUtil = require( 'mongoUtil' );

mongoUtil.connectToServer( function( err ) {
  // start the rest of your app here
} );

然后,当我在应用程序的另一个模块中尝试以下操作时:

const db = mongoDB.getDb();

router.post('/', (req, res, next) => {
    console.log(db);
    next();
})

日志未定义

日志上写着未定义,因此我没有DB实例。

为什么这不起作用?我该如何解决这个问题?

共有1个答案

越胤
2023-03-14

好啊所以,这可能是使用了一些过时的Mongo,但这就是我如何解决DB的单例部分的方法。免责声明:这是Mongo和Ecmascript 6.0的个人学习项目,所以不确定它是否遵循了最佳实践,但它是有效的。

首先,数据库连接:personnaDB。js

/************  Copyright ************/
/* Year: 2016
 * Author: David Espino
*/
"use strict"
// Imports
const url             = require('url'),
      connectionUrl   = process.env.CONNECTION_STRING || 'mongodb://localhost:27017/personna',
      parsedUrl       = url.parse(connectionUrl),
      Db              = require('mongodb').Db,
      Server          = require('mongodb').Server,
      Connection      = require('mongodb').Connection,
      Q               = require("q"),
      mongoose        = require("mongoose"),
      dao             = require('./personnaDao'),
      autoIncrement   = require( 'mongoose-auto-increment' );



// Symbol Keys
const _connKey = Symbol();
const _connInfoKey = Symbol();
const _monConnKey = Symbol();
const _dataModelsKey = Symbol();
const _autoIncrementKey = Symbol();

/**
 * This class represents the DB Connection
 */
class PersonnaDb {
  /**
   * Class Constructor
   * @return {[type]} [description]
   */
  constructor() {
    let mongoObject = null;
    this[_connInfoKey] = {
      host:     parsedUrl.hostname,
      port:     parseInt(parsedUrl.port, 10),
      name:     parsedUrl.pathname.substr(1),
      user:     parsedUrl.auth ? parsedUrl.auth.split(':')[0] : null,
      password: parsedUrl.auth ? parsedUrl.auth.split(':')[1] : null
    };
    this._connInstance = null;
  }

  /**
   * Opens the DB connection using regular mongo db access
   * @return {[type]} [description]
   */
  openConnection() {
    let deferred = Q.defer();
    if (this[_connKey]) {
      console.log('---> not need to create instance');
      deferred.resolve(this[_connInfoKey]);
    } else {
      let $this = this;
      const mongoObject = new Db('your-db', new Server(this[_connInfoKey].host, this[_connInfoKey].port, { auto_reconnect: true }));
      mongoObject.open(function(error, databaseConnection) {
        if (error) throw new Error(error);
        console.log('---> Succesfully CREATED connection');
        $this[_connKey] = databaseConnection;
        // Initialize auto increment
        autoIncrement.initialize(databaseConnection);
        $this[_autoIncrementKey] = autoIncrement;
        deferred.resolve($this);
      });
    }
    return deferred.promise;
  } 

  /**
   * Opens a Mongo db connection
   * @return {[type]} [description]
   */
  openMongooseConnection() {
    mongoose.connect(connectionUrl); 
    // set the identity plugin
    autoIncrement.initialize(mongoose.connection);
    this[_autoIncrementKey] = autoIncrement;

    // CONNECTION EVENTS
    // When successfully connected
    mongoose.connection.on('connected', function () {  
      console.log('Mongoose default connection open to ' + parsedUrl);
    }); 

    // If the connection throws an error
    mongoose.connection.on('error',function (err) {
      console.log('Mongoose default connection error: ' + err);
    });

    // When the connection is disconnected
    mongoose.connection.on('disconnected', function () {
      console.log('Mongoose default connection disconnected');
    });

    // If the Node process ends, close the Mongoose connection
    process.on('SIGINT', function() {
      mongoose.connection.close(function () {
        console.log('Mongoose default connection disconnected through app termination');
        process.exit(0);
      });
    });

    this[_dataModelsKey] = dao.PersonaDataModels.GetModels(this[_autoIncrementKey]);
   // require('../models/data/bodySectionModel');
  }

  dataModels() {
    return this[_dataModelsKey];
  }
}

module.exports.PersonnaDb = PersonnaDb;

第二...服务设置(我的dbconnect层)

服务

const ModifierService  = require('./modifierService').ModifierService;
const BodySectionService  = require('./bodySectionService').BodySectionService;
module.exports = (dbConnection) => {
  return {
    Modifier: new ModifierService(dbConnection),
    BodySection: new BodySectionService(dbConnection),

  }
}

服务示例(它基本上初始化了mongo Model.BodySectionService.js

class BodySectionService extends BaseService {

  constructor(db) {
    super(db.dataModels().BodySection); // this is the mongo model with the schema etc
  }

然后进行DB初始化(并将DB连接作为单例对象传递)

应用程序。js

var express = require('express');
const PersonnaDb = require('./dao/personnaDb').PersonnaDb;
const dbConnection = new PersonnaDb();

var app = express();
// Open DB Connection
dbConnection.openMongooseConnection();
// get the services
const services = require('./services/include')(dbConnection);

// // This is the piece that I was not totally sure, making this available on the app
app.set('services', services);
app.set('dbAccess', dbConnection); 

这就是我如何使用它:

身体部分Controller.js

router.get('/', function(req, res, next) {
  const bodySectionProxy = req.app.get("services").BodySection;
  const logger = req.app.get("customLogger");
  var result = bodySectionProxy.getBodySections({}).then((result) => {
    res.json(result);
  })
  .fail((err) => {
    logger.logError(err);
    res.json(err.message);
  })
  .done();
});

module.exports = router;

我已经排除了如何在服务上设置模型的路径,因为您的问题只询问如何设置数据库。但如果你需要我,我也可以用这个来扩展答案。

希望这能给你一个想法。

 类似资料:
  • 本文向大家介绍C ++程序在STL中实现配对,包括了C ++程序在STL中实现配对的使用技巧和注意事项,需要的朋友参考一下 Pair是一个简单的容器,由两个数据对象组成: 可以分配,比较和复制对。它用于将两个类型可能不同的值组合在一起。 语法为:pair <数据类型1,数据类型2>变量名称(数据值1,数据值2)。 算法 范例程式码 输出结果

  • 我想在应用程序运行时找到我的对象大小。我想用千分尺在Grafana中显示我的对象大小。 我的对象像人、学生、...... 我该怎么办? 对象大小像文件大小、对象体积

  • 我想将聊天应用程序与我的instagram类似的项目集成在一起。我的主要目标是为这个网站的用户提供实时聊天的可能性。我有以下代码,但我一直得到的错误: 这些观点。py: 路由。派克 项目根目录中的asgi.py: 我正在关注Django频道官方网站上的教程。我还试图定制我的消费者,将其保存在数据库中,其模型如下: 来自django。db从django导入模型。contrib。auth。模型导入用户

  • 问题内容: 在Android应用中实施应用内结算似乎非常复杂。我该怎么办?SDK中的示例应用程序只有一个Activity,对于像我这样的具有多个Activity的应用程序来说,这过于简化了。 问题答案: 好吧,我将尝试解释我的经历。我不认为自己是专家,但是几天我都伤透了脑筋。 对于初学者来说,我很难理解示例和应用程序的工作流程。我认为从一个简单的示例开始应该会更好,但是将代码分成几小段并且不知道是

  • 我是一个初学者,我只是找不到一个可行的解决方案。 我想做的是:用户输入用户名和密码,然后应用程序登录到一个网站。如果登录失败,则返回false和正确消息,否则返回true并继续执行下一个活动(获取另一个站点,解析html并显示内容)。 我的难题是:如何检测成功登录? 这是我的密码 LoginActivity的相关代码: 身份验证类中的方法: 由于我获得了200(OK)状态,我认为POST的代码工作