【问题标题】:Mongoose Typescript Class猫鼬打字稿类
【发布时间】:2020-05-11 01:16:23
【问题描述】:

下面的类抛出错误

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

【问题讨论】:

    标签: typescript mongoose


    【解决方案1】:

    你可以如下使用它。

    import { connect, Mongoose } from 'mongoose';
    //...
    private db: Mongoose;
    //...
    this.db = await connect(uri, { useNewUrlParser: true });
    

    【讨论】:

      【解决方案2】:

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

      希望对你有帮助

      【讨论】:

        【解决方案3】:

        我检查了文档:这是saying:

        connect() 函数也接受一个回调参数并返回一个承诺。

        mongoose.connect(uri, options, function(error) {
          // Check error in initial connection. There is no 2nd param to the callback.
        });
        
        // Or using promises
        mongoose.connect(uri, options).then(
          () => { /** ready to use. The `mongoose.connect()` promise resolves to mongoose instance. */ },
          err => { /** handle initial connection error */ }
        );
        

        如您所见,它实际上返回了一个 Promise,而这个 Promise 解析为 mongoose 实例

        我也查了猫鼬的index.d.ts,发现是:

        /**
         * Opens the default mongoose connection.
         * Options passed take precedence over options included in connection strings.
         * @returns pseudo-promise wrapper around this
         */
        export function connect(uris: string, options: ConnectionOptions, callback: (err: mongodb.MongoError) => void): Promise<Mongoose>;
        export function connect(uris: string, callback: (err: mongodb.MongoError) => void): Promise<Mongoose>;
        export function connect(uris: string, options?: ConnectionOptions): Promise<Mongoose>;
        

        所以看起来它返回了Promise&lt;Mongoose&gt;,并且由于您使用的是async/await,因此解析值将只是Mongoose。

        顺便说一句,不确定你在这里做什么,但我建议在连接数据库时按照文档says 进行操作:

        mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true });
        const db = mongoose.connection;
        db.on('error', console.error.bind(console, 'connection error:'));
        db.once('open', function() {
          console.log('Successfully connected to db')
        });
        

        您的this.db 可能应该等于mongoose.connection 类型为mongoose.Connection,而不是mongoose.connect(...) 的解析结果?

        希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 2016-02-05
          • 1970-01-01
          • 2016-04-01
          • 1970-01-01
          • 2017-04-11
          • 2017-01-20
          • 2021-01-05
          • 2021-10-05
          • 2016-06-14
          相关资源
          最近更新 更多