【发布时间】: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