【问题标题】:Node.JS + Typescript - Valid to set database configuration with module.exportsNode.JS + Typescript - 使用 module.exports 设置数据库配置有效
【发布时间】:2020-05-06 18:06:34
【问题描述】:

我在我的 node.js 应用程序中使用 Mongoose(用 Typescript 编写)。

Mongoose docs clearly show how to connect to their DB like this,但是我希望配置位于单独的文件中,而不是我的 index.js。

这样做是否有效,即module.exports,或者我应该注意另一种更新的方法:

import mongoose = require('mongoose');

const server = '127.0.0.1:27017';
const database = 'test';

class Database {
  constructor() {
    this._connect()
  }

_connect(): void {
     mongoose.connect(`mongodb://${server}/${database}`)
       .then(() => {
         console.log('Database connection successful')
       })
       .catch(err => {
         console.error('Database connection error')
       })
  }
}

module.exports = new Database()

我想知道的另一件事是 _connect() 只有在我将它导入其他文件时才会被调用 - 还是 module.exports = new Database() 会自动运行该构造函数?

任何帮助表示赞赏。

谢谢

【问题讨论】:

    标签: node.js typescript mongoose


    【解决方案1】:

    您可以使用 convict (https://www.npmjs.com/package/convict) 之类的库来创建配置持有者。 您可以在此处指定应用程序的所有配置。 您的 mongoFactory.ts 可以简单地包含一个充当 Mongoose 实例的服务工厂的函数。

    这是一个避免所有Ts熵的js示例

    module.exports = config => {
     // create a new Mongoose instance
     // setup the mongoose instance based on the configuration
     // check for problems and in case let the caller know
     // return the mongoose instance
    } 
    

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 2014-02-06
      • 2011-05-31
      • 2019-01-13
      • 2020-05-04
      相关资源
      最近更新 更多