1

I'm trying to update a database using Mongoose, but I'm getting this Network error while running my node app.

const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/fruitsDB")
const fruitsSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "Why no Name?"]
    },
    rating: {
        type: Number,
        min: 1,
        max: 10
    },
    review: String
 });
 const Fruit = mongoose.model("Fruit", fruitsSchema)
Fruit.find(function(err, fruits){
    if(err){
        console.log(err)
    }
    
    
    else{
        mongoose.connection.close();
        
        fruits.forEach(function(fruit){
            console.log(fruit.name)
        })
    }
})
Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err){
    if(err){
        console.log(err)
    }
    else{
        console.log("Successfully updated the document")
    }
})

Error: Commnad line error while running the node app

MongoNetworkError: connection establishment was cancelled
    at connectionFailureError 
    at CancellationToken.<anonymous> 
    at Object.onceWrapper (node:events:641:28)
    at CancellationToken.emit (node:events:527:28)
    at ConnectionPool.close 
    at Server.destroy 
    at destroyServer 
    at eachAsync

It's a simple Node app created using Mongoose.

Ayush Parui
  • 13
  • 1
  • 4
  • Similar question was answered [here](https://stackoverflow.com/questions/50173080/mongonetworkerror-failed-to-connect-to-server-localhost27017-on-first-connec) – Abdurrahim Ahmadov Jun 25 '22 at 15:41
  • Why are you closing the connection in the find() method, ideally it is wrong. You have to connect the mongoose server in the index(node server) file. So you don't need to connect to each controller. – Neeraj Kumar Sep 29 '22 at 04:50

8 Answers8

1

If you warp mongoose.connection.close() in a timeout the error won't happen. I think its because the connection is getting closed while the operations are not done yet.

I tried setting it to a lower number and got the same error, but 5 is fine. You may need to set a bigger number if you have a lot going on.

setTimeout(() => {
    mongoose.connection.close();
}, 5);
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
1

☑️Solution to the establishing relationship problem between Amy and Pineapple☑️ ERROR Line: MongoNetworkError: connection establishment was cancelled at connectionFailureError

const mongoose = require("mongoose");


mongoose.connect("mongodb://localhost:27017/fruitsDB",{useNewUrlParser: true});
 
const fruitSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "Please check your data entry, no name specified!"]
    },
    rating: {
        type: Number,
        min: 1,
        max: 10
    },
    review: String
});
 
const Fruit = mongoose.model("Fruit", fruitSchema);
 
const pineapple = new Fruit({
    name: "Pineapple",
    rating: 9,
    review: "Great fruit"
});
 
 
const personSchema = new mongoose.Schema({
    name: String,
    age: Number,
    favouriteFruit: fruitSchema
});
 
const Person = mongoose.model("Person", personSchema);
 
const person = new Person({
    name: "Amy",
    age: 12,
    favouriteFruit: pineapple
});
 
pineapple.save();
person.save();

You just need to save both the pineapple and the person together in the end and it worked for me.

0

Calling the find function last worked for me. I mean, like this -

Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err){
    if(err){
        console.log(err)
    }
    else{
        console.log("Successfully updated the document")
    }
})
Fruit.find(function(err, fruits){
    if(err){
        console.log(err)
    }
    
    
    else{
        mongoose.connection.close();
        
        fruits.forEach(function(fruit){
            console.log(fruit.name)
        })
    }
})

Closing the connection should be at end which is the reason why the code is not getting properly executed.

Sam
  • 1
0

I tried Calling the find function last but still getting the same error like this:

MongoNetworkError: connection establishment was cancelled

I don't know how to tackle this issue when it occurs in a running application but for now if you want to just insert the docs in collection then just comment the .find method completely and then run the application it will be inserted successfully and then comment the .updateOne method and uncomment the .find method by doing you will be successfully added the docs and could get the find result.

I did the same!

OR

I found out that for some reason .find method gets executed before .updateOne so the connection were being closed before the collection gets updated.

So, if we do this it works.

Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err) {
  if (err) {
    console.log(err)
  } else {
    Fruit.find(function(err, fruits) {
      if (err) {
        console.log(err)
      } else {
        mongoose.connection.close();
              
        fruits.forEach(function(fruit) {
          console.log(fruit.name)
        })
      }
    });
    console.log("Successfully updated the document")
  }
})
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

You can't close the connection in the find method. You are not able to interact with the db after you closed the connection. Just put mongoose.connection.close() at the end.

0

Just Do something like this:

`People.insertMany([man1, man2, man3], 
   function (err) {
     if (err) {
       console.log(err);
     } else {
       console.log("Successfully saved all 
       models in the database");
       mongoose.connection.close();
      }
 });`

Closing the connection inside insertmany worked for me

the_h_u_z
  • 1
  • 2
0

After reading some solutions the TL:DR is: the mongoose.disconnect();, it's the one causing problems, the connection is being terminated before you can update anything

8koi
  • 182
  • 1
  • 1
  • 10
0

You should be careful while using crud methods on database. Because those methods are asynchronous.
In your case the find method executed first and closed the database connection prior to updateOne method.

Solution: You can solve that by simply changing the logic in your code like embedding find method inside updateOne method or viseversa according to your need.(By embedding we are making a way to execute them in order)

Fruit.find(function(err, fruits) {
  if (err) {
    console.log(err)
  } else {
    fruits.forEach(function(fruit) {
      console.log(fruit.name)
    })

    Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err) {
      if (err) {
        console.log(err)
      } else {
        mongoose.connection.close();
        console.log("Successfully updated the document")
      }
    })
  }
})
Tyler2P
  • 2,324
  • 26
  • 22
  • 31