typescript - 猫鼬打字稿类
问题描述
下面的类抛出错误
类型 'typeof import("mongoose")' 缺少来自类型 'Db' 的以下属性:serverConfig、bufferMaxEntries、databaseName、options 等 37 个。
我无法找出 mongoose.connect 的返回类型是什么。
import mongoose from "mongoose";
import {Db} from "mongodb";
interface MongoDbConfig {
server: String,
port: String,
dbName: String;
}
// TODO: make singelton
class MongoDb {
private db : Db;
private _server : String;
private _port : String;
private _dbName : String;
constructor(config: MongoDbConfig){
this._server = config.server;
this._port = config.port;
this._dbName = config.dbName
}
public async connect() {
const uri = "mongodb://"+this._server+":"+this._port+"/"+this._dbName;
this.db = await mongoose.connect(uri, { useNewUrlParser: true }); // error
console.log(typeof this.db)
console.log("Connected to db");
return this.db;
}
public getDb(){
return this.db;
}
}
解决方案
问题似乎来自在db
变量代码中键入声明。类型定义提到该connect
函数返回Promise<Mongoose>
但this.db
具有Db
类型而不是Mongoose
.
这可能会解决问题
private db: mongoose.Mongoose; // change from Db to mongoose.Mongoose
// ...
this.db = await mongoose.connect(uri, { useNewUrlParser: true });
希望能帮助到你
推荐阅读
- python - Elasticsearch for python 无法建立与 Elastic Cloud 的新连接
- odata - 按最新数据过滤 OData
- karate - 空手道场景大纲和示例
- javascript - Firestore 分页向后总是转到第一条记录
- reactjs - 有没有使用 React.memo/PureComponent 比不使用它的性能更差的例子?
- excel - VBA - 如何从一列中随机选择 10% 的行,确保它们不同并将 Y 放在 B 列中?
- php - 从 curl 查询中获取数据
- javascript - react-native android fetch json停止工作
- c# - Google 驱动器 API 错误 400:redirect_uri_mismatch 与 Unity
- python - Itertools python 2.7组合在终端中获得输出“Killed”。Aarch64 linux