如何从猫鼬连接获取主机/端口?

时间:2019-09-25 15:38:02

标签: node.js mongodb typescript mongoose

我正在通过NodeJS上的猫鼬v5.7.1连接到MongoDb,并且需要获取Connection的主机和端口,但是TypeScript会引发此错误“属性'host'在类型'Connection'上不存在。ts(2339 )” ,当我这样尝试时:

import mongoose from "mongoose"
...
private database: typeof mongoose
...
database = await mongoose.connect(mongoDbUri, {useNewUrlParser: true, useUnifiedTopology: true})
database.connection.host

但是,在Mongoose文档上, Connection 类具有属性 host port

  

https://mongoosejs.com/docs/api/connection.html#connection_Connection-host

关注我的 package.json

  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "express-jwt": "^5.3.1",
    "mongoose": "^5.7.1",
    "validator": "^11.1.0"
  },
  "devDependencies": {
    "@types/cors": "^2.8.6",
    "@types/express": "^4.17.1",
    "@types/express-jwt": "0.0.42",
    "@types/mongoose": "^5.5.18",
    "mongodb-memory-server": "^5.2.5",
    "nodemon": "^1.19.2",
    "ts-node": "^8.4.1",
    "tslint": "^5.20.0",
    "typescript": "^3.6.3"
  }

出什么问题了,我该如何解决?

谢谢

1 个答案:

答案 0 :(得分:0)

类型错误。通过写(conn.connection as any).host

绕过