首页 > 解决方案 > 猫鼬打字稿类

问题描述

下面的类抛出错误

类型 '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;
    }
}

标签: typescriptmongoose

解决方案


问题似乎来自在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 }); 

希望能帮助到你


推荐阅读