猫鼬打字稿课

时间:2020-01-24 17:19:47

标签: typescript mongoose

下面的类抛出错误

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

3 个答案:

答案 0 :(得分:0)

我检查了文档:这是saying

connect()函数还接受一个回调参数并返回一个Promise。

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 */ }
);

如您所见,它实际上返回一个承诺,并且这个承诺解析为猫鼬实例

我也检查了猫鼬的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<Mongoose>,并且由于您正在使用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的{​​{1}},而不是mongoose.Connection的解析结果?

希望这会有所帮助。

答案 1 :(得分:0)

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

希望有帮助

答案 2 :(得分:0)

您可以按如下方式使用它。

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