This question here is closely related but the question and the answer are not very related at all. However, in the comments of that OP's post there is the difficulty of working with .close()... That is where the similarities end.
The issue comes from trying to create an api using the direct nodejs mongodb driver 3.9. I have the client call in the controller because putting it in the server and calling to the client when needed constantly creates a "connect error" so here it is in the controller for full context.
whenever I use .close() in the collection client call it will run once and then every other call after that will cause an error Topology is closed. So, for now I commented it out. I am wondering what is causing this and what might I being doing incorrectly causing this error?
The documentation per the driver states to use this and what the purpose is but it is breaking my api repeatedly.
const express = require('express');
const router = express.Router();
import { MongoClient, MongoCallback, MongoError, MongoNetworkError } from 'node_modules/mongodb';
// const MongoClient = require('node_modules/mongodb').MongoClient;
const dbName = 'HealthCheckup';
const documentName = 'userProfile';
const assert = require('assert');
const url = `mongodb+srv://UserDB:h7srvvvvvvvHFd8@vvvvvvvvvai-cvyrh.azure.mongodb.net/${dbName}?retryWrites=true&w=majority`;
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true});
const findUsers = (client, callback) => {
// Get the documents collection
const collection = client.collection(documentName);
// Insert some documents
collection.find({}).toArray( (err, result) => {
// console.log('err **** -------- ', err);
// console.log('Result -------- ', result);
callback(err, result);
});
}
const createUser = (client, callback, req) => {
// Get the documents collection
const collection = client.collection(documentName);
// Insert some documents
collection.insertOne({
name: req.body.name,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
tokenId: req.body.tokenId,
userPhoto: req.body.userPhoto
}, (err, result) => {
// console.log('err **** -------- ', err);
// console.log('Result -------- ', result);
callback(err, result);
});
}
// localhost:4021/user
router.get('/', (req, res) => {
client.connect( err => {
const collection = client.db(dbName);
if (!err) {
console.log("Connected successfully to server.");
} else {
console.log('Error in DB connection : ', JSON.stringify(err, undefined, 2));
}
findUsers(collection, (err, result) => {
console.log('err 2222222 -------- ', err);
console.log('Result 2222222 -------- ', result);
if (!err) {
res.send(result);
} else {
console.log('Error retreiving user ', JSON.stringify(err, undefined, 2))
}
console.log('BREAKPOINT 00000000000000000');
// client.close();
});
});
});