1

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();
        });
    });
});
Christian Matthew
  • 4,014
  • 4
  • 33
  • 43

2 Answers2

1

You are trying to close the client in a request handler, but your client is global.

If you want to have a global client, do not close it in request handlers.

If you want to close the client in request handlers, create the client in the handler of the same request.

D. SM
  • 13,584
  • 3
  • 12
  • 21
  • can you help with a couple things. I was trying to mimic, per se, the mongoose implementation I see all over the internet for examples. The setup is usually they create a connection in the express server and then use that everywhere else. I keep getting an `connect error` that prevents me from doing that. So, I now have this abstraction that I am starting with. And you're saying that my client is global? Is it because I instantiate the class outside of the handler? I know it's duh but. Also, if I have something global because I may make these helpers where can or where should I close it? – Christian Matthew May 28 '20 at 18:26
  • also, how can I even verify that it is close? – Christian Matthew May 28 '20 at 18:26
  • You probably should not close the global client ever. – D. SM May 28 '20 at 18:30
  • ok i can live with that. do people mostly use a global client? – Christian Matthew May 28 '20 at 18:31
  • I do not write node but using the global client should be significantly more efficient, so I would expect many applications to do so. – D. SM May 28 '20 at 19:41
  • so now that I have this working would you be able to help with why I can't make a post request to the service? – Christian Matthew May 28 '20 at 19:51
  • 1
    Best for a separate question. – D. SM May 28 '20 at 20:11
0

There is a bug on MongoDb: reconnection to the client doesn't work. Seems like it will be fixed in version 4.0.0. For now it's beta. If you don't want to use the beta version then don't close the client. Or recreate it in handlers like it was proposed in previous answer.

Lana
  • 1,199
  • 7
  • 16