skip to Main Content

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.

6

Answers


  1. 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.

    Login or Signup to reply.
  2. 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")
      }
    })
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
  4. 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

    Login or Signup to reply.
  5. 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

    Login or Signup to reply.
  6. 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")
          }
        })
      }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search