An issue has been encountered during the process of disconnecting with mongoose

I'm new to mongodb/mongoose and javascript. When I try to use mongoose.disconnect, it throws an error

return new error_1.MongoNetworkError('connection establishment was cancelled'); ^ MongoNetworkError: connection establishment was cancelled "

below is the code snippet -

const mongoose = require("mongoose");

const mongoDB = "mongodb://127.0.0.1:27017/fruitsDB";

mongoose
    .connect(mongoDB,{
        useNewUrlParser:true,useUnifiedTopology:true
    })
    .then(() => console.log("MongoDB connected"))
    .catch((err) => console.error("error!!! - ",err));

const fruitSchema = new mongoose.Schema ({
    name:String,
    rating:Number,
    review:String
});

const Fruit = mongoose.model("Fruit",fruitSchema);

const fruit = new Fruit ({
    name:"Apple",
    rating:7,
    review:"pretty solid as a fruit"
});

// fruit.save();

const personSchema = new mongoose.Schema ({
    name:String,
    age:Number
});

const Person = mongoose.model("Person",personSchema);

const person = new Person ({
    name:"xyz",
    age:37
});

person.save();

const kiwi = new Fruit({
    name:"Kiwi",
    score:10,
    review:"The best fruit"
});

const orange = new Fruit({
    name:"Orange",
    score:4,
    review:"Too sour for me"
});

const banana = new Fruit({
    name:"Banana",
    score:10,
    review:"Weird texture"
});

// Fruit
//     .insertMany([kiwi,orange,banana])
//     .then( ()=> console.log("Succesfully saved all the fruits to fruitsDB"))
//     .catch( (err) => console.log(err));

async function getFruits() {
    const fruit = await Fruit.find({});
    mongoose.disconnect();
    return fruit;
}

const printFruitsName = async () => {
    const res = await getFruits();
    res.forEach((fruit) => console.log(fruit.name));
}

printFruitsName();

Please assist!

tldr: Attempted to close MongoDB using mongoose.disconnect() but encountered an error stating that the connection was not established

Is there a way to properly close the mongoose database connection?

Answer №1

When using mongoose.connect, it is important to remember that it operates asynchronously. This means that your application can continue executing the next line of code while the connection process is still ongoing.

However, since establishing a connection may take some time, there is a possibility that the application may progress to the .disconnect method before the connection is fully established.

To address this issue, make sure to move any code that follows after the mongoose.connect call inside the .then callback. This will ensure that the subsequent code is executed only after the connection has been successfully established.

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

What are the steps to achieve complete test coverage for my Angular login form? Encountering an issue with reading property 'subscribe' of undefined

Recently, I made adjustments to my login component to align more closely with Angular standards. However, upon testing, I encountered errors of this kind: Cannot read property 'subscribe' of undefined After using console.log for debugging pur ...

Be warned: Babel has detected a duplicate plugin or preset error

Currently, I am enrolled in a React course on Frontend Masters. As part of the course, we were tasked with modifying the Babel config to allow state instantiations like: state = {index: 0} in class components. However, when I executed the command: npm i ...

What is the best way to transfer form data to another function without causing a page refresh?

Currently, I am in the process of developing a series of web applications using REACT JS. One specific app I am working on involves a modal that appears upon a state change and contains a form where users can input their name along with some related data. ...

Converting an object of objects into an associative array using Javascript and JSON

Using AngularJS, I am sending this data to my API : $http.post('/api/test', { credits: { value:"100", action:"test" } }); Upon receiving the data in my nodeJS (+Express) backend, it appears as follows : https://i.stack.imgur.com/NurHp.png Why ...

Nested loops with synchronous calls running in parallel

Is there a way to make synchronous calls in two nested 'for' loops in Node.JS? I have an Asynchronous call, but I am unsure how to modify it to work synchronously and go to the next iteration when create_db is done! var new_items = []; f ...

Is there an issue with invoking Spring controller methods from JavaScript (via ajax) that is causing them

Using JavaScript to send a request to a method in Spring controller, the code looks like this: <script language="javascript" type="text/javascript"> var xmlHttp function show() { if(typeof XMLHttpReques ...

Guide: "Executing an AJAX button click using a Greasemonkey script"

(find below a solution) I created a Greasemonkey script that automatically clicks on a specific link within a target website. Initially, my script looked like this: var MyVar = $("a:contains('Save')"); if (MyVar && MyVar.length) win ...

Flask Modal fails to function properly in the absence of table data

I'm currently troubleshooting an issue with my modal on a Flask web app that utilizes a SQLite database. When trying to add new rows to the table using some JavaScript code, everything works perfectly unless the table is empty. In that case, I am unab ...

How can I locate a nested JSON object using AngularJS?

Having trouble accessing a nested JSON object and displaying it using AngularJS. Need some guidance on this issue! Here's the HTML: <div id="ng-app" ng-controller="AnalyticsCtrl"> <div ng-repeat="post in posts"> <span>{ ...

Run a script tag prior to displaying the modal

Currently, I am attempting to display a bootstrap modal with dynamic content. One of the values being passed to the modal is the HTML that should appear inside it. The issue I am facing is that within the HTML content being passed, there is a script tag t ...

What are the implications of storing data in the id attribute of an HTML element?

If I have a template where I need to loop and generate multiple div elements, each containing a button, how can I listen to clicks on these buttons individually? <div class="repeatedDiv"> <button class="reply-button"> </div> $(&apos ...

Enhancing an array of objects by incorporating properties using map and promises

I am encountering an issue with assigning a new property to each object in an array, which is obtained through an async function within a map method. Here is the code snippet that I am using: asyncFunction.then(array => { var promises = array.map(o ...

What could be the reason for the malfunction of this angular binding?

Looking at the HTML below: <input type="checkbox" name="person" [(ngModel)]="person.selected" /> This input is part of a ngFor loop. Testing has revealed that despite some values of selected being true and others false, all checkboxes appear check ...

The Singleton pattern is not compatible with ClientEncryption in Java 11.0.10+9 Red Hat, as it may cause a double free detected in tcache intermittently

Experiencing a situation where my Azure pod running JVM crashes after 12-13 hours of up-time with the following error: free(): double free detected in tcache 2 A fatal error has been detected by the Java Runtime Environment: SIGSEGV (0xb) at pc=0x00007f3e ...

What is the method to prevent the Submit Button from being active in CSS specifically on Firefox?

When I click this CSS in webpages on Chrome (OS: Windows), it works fine. However, Firefox (OS: CentOS7) does not seem to apply this CSS on webpages. How can I resolve this issue? Should I make adjustments in the CSS code below? #submit .btn.btn-primary ...

Issue encountered when attempting to trigger an ionic modal from a custom control in Google Maps

I am facing an issue with my custom Google map control in Ionic framework. I want the control to open a modal when clicked, but I keep getting an error "Cannot read property '$$destroyed' of undefined" when I try to do so. On the other hand, anot ...

Pressing the button element equipped with an event listener leads to the page being refreshed

I'm encountering an issue with my function in this JSFiddle window.addEventListener("load", init, false); function init() { let name = document.getElementById("name").addEventListener("blur", checkName, false); let startButton = document.getEl ...

Encountering a browser error when trying to access a C# method via AJAX: Javascript

I'm having trouble connecting to my Webservice. I keep getting an error 404, even though everything seems like it should be working fine. The issue started when I moved the code from my *.cshtml file into a separate .js file. The Javascript file is l ...

transfer properties to a dynamic sub element

I am currently working on a multi-step form project. I have successfully implemented the form so that each step displays the corresponding form dynamically. However, I am facing challenges in passing props to these components in order to preserve the state ...

The clash between mootools and jQuery

I'm facing an issue with a simple form on a page that loads both Mootools and JQuery. Even though JQuery is in no conflict mode, I am encountering problems. There's a form input named "name"-- <input class="required" id="sendname" name="send ...