我有一个需要连接到MongoDB的node.js的小型TypeScript应用程序:
module Engine
{
export class EngineCore
{
public launch()
{
var mongo = require('mongodb');
var client = mongo.MongoClient;
client.connect('mongodb://localhost:27017/', (error, db) => {this.onDBConnect(db)});
}
private onDBConnect(db)
{
}
}
}
现在,我知道我在连接回调上获得了Db
类,但我无法找到明确键入db
参数的方法Db
1}}类。我使用了mongodb
的DefinitelyTyped定义文件,它是这样的:
declare module "mongodb" {
export class MongoClient {
constructor(serverConfig: any, options: any);
static connect(uri: string, options: any, callback: (err: Error, db: Db) => void): void;
static connect(uri: string, callback: (err: Error, db: Db) => void): void;
}
export class Db {
constructor (databaseName: string, serverConfig: Server, dbOptions?: DbCreateOptions);
[...]
}
}
我尝试过这样导入:
module Engine
{
import MongoDB = require('mongodb');
[...]
}
但我收到以下错误:
error TS2136: Import declarations in an internal module cannot reference an external module.
有没有办法使用Db
类从模块外部进行显式输入?
答案 0 :(得分:1)
您是否尝试过像这样重新定位导入?以下编译并为我运行
import mongo = require('mongodb');
module Engine
{
export class EngineCore
{
public launch()
{
var client = mongo.MongoClient;
client.connect('mongodb://localhost:27017/', (error, db) => {
this.onDBConnect(db);
});
}
private onDBConnect(db:mongo.Db)
{
console.log("connected");
}
}
}
var x = new Engine.EngineCore();
x.launch();