【问题标题】:NodeJS: Controlling the order of loading modulesNodeJS:控制加载模块的顺序
【发布时间】:2021-10-08 19:21:00
【问题描述】:

这是场景: 我有 3 个文件(模块):

app.js

(async () => {
  await connectoDB();
  let newRec = new userModel({
    ...someprops
  });
  await newRec.save();
})();

app.ts 是项目的入口点。

database.ts

interface ConnectionInterface {
  [name: string]: mongoose.Connection;
}

export class Connection {
  public static connections: ConnectionInterface;

  public static async setConnection(name: string, connection: mongoose.Connection) {
    Connection.connections = {
      ...Connection.connections,
      [name]: connection,
    };
  }
}

export async function connectToDB() {
  const conn = await mongoose.createConnection('somePath');
  await Connection.setConnection('report', conn);
}

model.ts

const userSchema = new mongoose.Schema(
  {
    ..someprops
  },
);

const userModel = Connection.connections.report.model('User', userSchema);
export default userModel;

我想做的事:我需要有多个猫鼬连接,所以我在Connection 类(在database.ts)中使用了一个名为connections 的静态道具;每次我连接到数据库时,我都会使用 setConnection 将连接存储在提到的静态属性中,因此我可以从项目中的每个模块中通过其名称访问它,在这种情况下为 report

后来,在model.ts 中,我使用Connection.connections.report 访问连接report 来加载我的模型!

然后,当我运行app.ts 时,我收到以下合乎逻辑的错误:

const aggregationModel = Connection.connections.report.model('User', userSchema)
                                                ^
TypeError: Cannot read property 'report' of undefined

造成这种情况的原因(我认为)是,在 app.ts 中加载导入的模块时,.report 未声明,因为 app.ts 未完全运行(connectoDB() 定义了 .report 键) .

我提到的代码已被简化以防止复杂性。原版应用是快递应用!

现在,我应该如何解决这个错误?

提前致谢。

【问题讨论】:

    标签: javascript node.js typescript mongoose


    【解决方案1】:

    如果你稍微改变你的班级,你可以等待连接完成后再使用它。

    const connection = await Connection.getConnection()
    const model = connection.example
    
    ...
    
    class Connection {
      ...
    
      public static async getConnection() => {
        if (!Connection.connection) {
          await Connection.setConnection()
        }
    
        return Connection.connection
      }
    }
    

    【讨论】:

    • 我创建了一个函数为:public static getConnections() { return Connection.connections; }。并尝试访问报告,例如:Connection.getConnections().report,是否正确?这并没有改变。
    • 它没有进行任何更改,因为您实际上并没有更改任何内容,您只是返回了与以前相同的连接。您需要检查这些连接是否存在,并延迟解决承诺,直到它们真正被创建。在这种情况下,您只是从 getConnections 返回 undefined。
    • @Matriax 你能解释一下我应该如何等待吗?一个小代码也会有所帮助。谢谢你的时间:)
    • 更新了答案。
    猜你喜欢
    • 2015-07-06
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多