Mongo TypeError:MongoClient.close不是函数

时间:2018-03-30 02:59:47

标签: node.js mongodb express

我正在构建一个应用程序,在一段时间不活动后关闭它的数据库连接。问题是,我无法杀死它与MongoClient.close()的连接,因为它始终返回错误“TypeError:MongoClient.close不是函数”。我做错了什么?

const MongoClient = require("mongodb").MongoClient;
let mongo = {};
let db;
let disconnect; //Used to prevent mongo from reconnect.
mongo.disconnect = () => {
disconnect = true;
try {
    MongoClient.close();
} catch (error) {
    console.warn("Error closing connection to Database =", error);
    throw {
        statusCode: 404,
        error: error.toString(),
        reason: "",
        details: ""
    };
}
}

的package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "test API.",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "test": "nodemon äpp.js
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "henriquelborges",
  "license": "ISC",
  "bugs": {
    "url": ""
  },
  "homepage": "",
  "dependencies": {
    "body-parser": "^1.18.2",
    "consign": "^0.1.6",
    "dotenv": "^5.0.1",
    "express": "^4.16.3",
    "express-validator": "^5.0.3",
    "mongodb": "^2.2.33"
  }
}

2 个答案:

答案 0 :(得分:1)

如果db用作Mongo DB连接实例,请尝试使用dB.close()而不是MongoClient.close()。

答案 1 :(得分:1)

module.exports = (callback, collectionName) => {
    mongoClient.connect(connectionUrl, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then((connection) => {
        const db = connection.db(dbName);
        const collection = db.collection(collectionName);

        callback(collection, ObjectId);

        connection.close();
    });
}