Exception: Closing the database connection failed: db.close is not a callable

I have this Node.js application that utilizes MongoDb:

const MongoClient = require('mongodb').MongoClient;

const demoPerson = { name:'Jane', lastName:'Doe' };
const findKey = { name: 'Jane' };

MongoClient.connect('mongodb://127.0.0.1:27017/demo', { useNewUrlParser: true }, function(err, client) {
  const db = client.db('demo');
  if(err) throw err;
  console.log('Connection successful');
  //console.log(db);

  const collection = db.collection('people');
  collection.insert(demoPerson, function(err, docs) {
    console.log('Inserted:', docs[0]);
    console.log('ID:', demoPerson._id);

    collection.find(findKey).toArray(function(err, results) {
      console.log('Found the following results:', results);

      collection.remove(findKey, function(err, results) {
        console.log('Deleted person successfully');

        db.close();
      });
    });
  });
});

However, running it gives me this error message:

TypeError: db.close is not a function

I am having trouble figuring out why it doesn't work. Can someone assist me?

Answer №1

According to the comment made by @Neil Lunn, it is recommended to use client.close() instead of db.close().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Node Express for RESTful API creates a seamless error handling system

I have been working on developing a series of RESTful API services using Node.js Express. Whenever an error occurs, it is accompanied by a stack-trace with the following message: Error: No default engine was specified and no extension was provided. I h ...

Ways to access information from doc.data()

<template> <div> {{ id }} {{ title }} </div> </template> <script> import { useRoute } from 'vue-router' import 'firebase/firebase-firestore' import { db } from '@/fdb' export default ...

Does writing JavaScript code that is easier to understand make it run slower?

While browsing the web, I stumbled upon this neat JavaScript program (found on Khan Academy) created by another user: /*vars*/ frameRate(0); var Sz=100; var particles=1000; scale(400/Sz); var points=[[floor(Sz/2),floor(Sz/2),false]]; for(var i=0;i<part ...

Error in decoding with RSA padding check PKCS1 OAEP MGF1 routines in JSencrypt for Node.js Crypto

I've been utilizing the NodeJS Crypto module for encryption and decryption with RSA on the backend, while using JSencrypt for frontend RSA operations. The problem arises when I attempt to encrypt data on the frontend using a public key, resulting in ...

Create a fresh trail underneath the overlay image

When utilizing fabric.js to draw a new path with isDrawingMode: true enabled (seen on the right side of the screenshot), I am encountering an issue where the path appears above my overlay image, which is a transparent png. https://i.stack.imgur.com/R3fGn. ...

When attempting to launch my application on Heroku, I consistently encountered the following error code: 'ERR_DLOPEN_FAILED'

As a new user on Heroku, I am currently working on building an app with react (Node.js). Even though Heroku confirms that my app has been successfully deployed, the app itself does not seem to be deployed despite showing a deploy success message: "Deploy ...

Using MongoMapper with Rails to efficiently render arrays in views

In my Rails application, I have a controller that retrieves data from MongoDB. The specific field I need is actually an array, and I want to display it in an erb view. Currently, my workaround involves setting the JavaScript variable directly in the view ...

Could the issue at hand possibly stem from the fact that the router isn't fully operational? It appears that router.query

Having trouble retrieving the parameters from the URL using router.query. I've tried various approaches but keep getting an undefined result. It seems like I'm on the right track, though. Highlighted query param in yellow... https://i.stack.img ...

Several jquery libraries are experiencing malfunctions

<head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $(".slidingDiv").hide(); $(".show_hide").show().click ...

Vue Eslint Extension

My current project utilizes the eslint vue plugin with specific rules set in place. "rules": { "vue/html-closing-bracket-newline": ["error", { "singleline": "never", "multiline": "always" }], "vue/html-closi ...

What are the steps to developing a chat application with MERN stack or another straightforward method?

What is the best way to develop a chat application for direct communication between two individuals? For instance, imagine a website with numerous producers where a consumer wishes to engage in a live chat with a specific producer. Any ideas on how to ach ...

Altering the dimensions of a <div> based on the retrieved data

I am currently retrieving data from an API and displaying certain properties using mapping. I would like to adjust the width of the component based on the value of these properties. <h5> <span className="viewcount" ref={boxSize}> ...

Encountering issues with link button redirection

I have a question regarding a Link element and CustomButton element with an onClick handler. < Link to = "/dashboard" style = { linkStyles } > < CustomButton text = "Login" onClick = { handleSubmit } /> < /Link> The code ...

Trouble arises when implementing AJAX in conjunction with PHP!

I am facing an issue with my PHP page which collects mp3 links from downloads.nl. The results are converted to XML and display correctly. However, the problem arises when trying to access this XML data using ajax. Both the files are on the same domain, b ...

Restrict the character count in the input field according to its width

Is there a way to restrict the number of characters in an input field based on its width? I have a dynamic input field with varying widths and I would like users to be able to type without their text extending outside of the input boundary. Using maxLeng ...

Manipulating deeply nested state data in Vuex actions can be a challenge

When working in the store, I have an action that updates certain data. The action is structured like this: setRoomImage({ state }, { room, index, subIndex, image }) { state.fullReport.rooms[room].items[index].items[subIndex].image = image; co ...

Switching Next.js route using pure JavaScript

Currently, I am facing a challenge in changing the route of a Next.js application using vanilla Javascript. In order for the code to be compatible with Chrome Dev Tools, I cannot dynamically change the route with Next.js and instead must find a solution us ...

Troubleshooting issue: Click function not responding inside Bootstrap modal

Below is the JavaScript code for my click function $(".addPizza").on("click", function(event) { event.preventDefault(); console.log("hello") let userId = $("#userId").attr("data-id"); let pizzaRecipe = $('#pizza-recipe').val().trim(); ...

Enhance your iPhone web app with high-resolution retina images!

As I develop a mobile web application accessible on any smartphone, I have the index.html file available for review: The app includes 2 jQuery functions. One detects if the user is using an iPhone and displays a bubble with instructions to add it to the h ...

Exploring how to read class decorator files in a Node.js environment

I've developed a custom class decorator that extracts permissions for an Angular component. decorator.ts function extractPermissions(obj: { [key: 'read' | 'write' | 'update' | 'delete']: string }[]) { re ...