Mongonetworkerror:连接机构被取消

发布于 2025-02-11 01:13:25 字数 1301 浏览 2 评论 0 原文

我正在尝试使用Mongoose更新数据库,但是在运行节点应用程序时,我会遇到此网络错误。

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")
    }
})

错误:运行节点应用程序时,Commnad Line错误

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

是使用Mongoose创建的简单节点应用程序。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

怪我鬧 2025-02-18 01:13:25

如果您扭曲 mongoose.connection.close()在超时,则不会发生错误。我认为这是因为连接尚未完成,但尚未完成操作。

我尝试将其设置为较低的数字,并遇到相同的错误,但是5很好。如果您有很多事情要做,则可能需要设置更大的数字。

setTimeout(() => {
    mongoose.connection.close();
}, 5);

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);
小嗷兮 2025-02-18 01:13:25

Amy和Pineapple☑️错误线:MongonetWorkerror:连接机构在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();

您只需要保存菠萝和人 最后 对我有用。

☑️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.

败给现实 2025-02-18 01:13:25

呼叫查找功能上次对我有用。我的意思是,这样 -

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)
        })
    }
})

关闭连接应结束,这就是为什么代码无法正确执行的原因。

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.

顾忌 2025-02-18 01:13:25

我尝试将查找功能持续调用,但仍会遇到这样的错误:

MongoNetworkError: connection establishment was cancelled

我不知道该问题在运行应用程序中发生时如何解决该问题,但是目前,如果您只想将文档插入集合中。访问方法,然后运行应用程序将成功插入该应用程序,然后评论 .updateOne 方法和删除。

我做了相同的!

,否则

我发现出于某种原因。输入方法在 .updateone 之前被执行,因此在收集更新之前,连接已关闭。

因此,如果我们这样做它有效。

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")
  }
})

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")
  }
})
千鲤 2025-02-18 01:13:25

您无法关闭查找方法中的连接。关闭连接后,您无法与DB进行交互。只需将 mongoose.connection.close()放在最后即可。

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.

屋顶上的小猫咪 2025-02-18 01:13:25

只需做这样的事情:

`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();
      }
 });`

关闭 insertmany内部的连接对我有用

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

嗫嚅 2025-02-18 01:13:25

阅读了一些解决方案后TL:DR是: mongoose.disconnect(); ,这是引起问题的一种

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

虫児飞 2025-02-18 01:13:25

在数据库上使用CRUD方法时,应该要小心。因为这些方法是异步的。
在您的情况下,查找方法先执行并在更新方法之前关闭数据库连接

解决方案:您可以通过简单地更改代码中的逻辑(例如嵌入 find 方法 update> updateOne 方法方法或根据您的需要)来解决该问题。(通过嵌入我们正在做一种方法按顺序执行它们)

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")
      }
    })
  }
})

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")
      }
    })
  }
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文