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
Calling the find function last worked for me. I mean, like this –
Closing the connection should be at end which is the reason why the code is not getting properly executed.
I tried Calling the find function last but still getting the same error like this:
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.
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.Just Do something like this:
Closing the connection inside
insertmany
worked for meAfter 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 anythingYou 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 toupdateOne
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)