Reputation: 1
When i try to close the connection between NodeJS and MongoDB cluster i get mongoClient.close is not a function. Please help
Node JS MongoDB code
const mongoClient = require("mongodb").MongoClient;
exports.getInfo = async (czytnik_id) => {
return new Promise((resolve, reject) => {
mongoClient.connect(process.env.URI, { useUnifiedTopology: true }, (err, db) => {
if (err) reject(err);
const dbo = db.db('TTI');
const res = dbo.collection('3P').findOne({ id: czytnik_id });
mongoClient.close()
resolve(res);
});
});
}
Upvotes: 0
Views: 462
Reputation: 102617
From the doc mongodb - npm and Connection guide, MongoClient
is a class. You need to create a client instance, the .close
method is an instance method.
Example:
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
// the following code examples can be pasted here...
return 'done.';
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
Upvotes: 0
Reputation: 1213
According to the docs, the callback in MongoClient.connect()
takes an error and a connected client instance, which is the one to be closed. In your case, it seems to be db
, so try db.close()
instead of mongoClient.close()
.
Upvotes: 1