【问题标题】:Why are all my Mongoose requests timing out?为什么我所有的 Mongoose 请求都超时了?
【发布时间】:2021-05-16 20:09:04
【问题描述】:

我的 Mongoose 请求从昨天开始就全部超时了。

我的互联网连接正常,和往常一样,我的源代码没有改变。

所以,我认为这一定是我的依赖项或 MongoDB 本身的问题。

最小可重现示例:

const mongoose = require('mongoose')


const mongoURL = //replace this comment with your own Mongo URL

mongoose.connect(mongoURL, { 
  useNewUrlParser: true, 
  useUnifiedTopology: true, 
  useFindAndModify: false, 
  useCreateIndex: true 
})

const exampleSchema = new mongoose.Schema({
  title: String,
  author: String
})

const Example = mongoose.model('Example', exampleSchema)

const exampleOne = new Example({
  title: 'Don Quixote',
  author: 'M. Cervantes'
})

exampleOne.save().then(res => console.log(res))

mongoose.connection.close()

运行上述示例的完整错误跟踪:

(node:18284) Warning: Accessing non-existent property 'MongoError' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
(node:18284) UnhandledPromiseRejectionWarning: MongooseError: Operation `examples.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (G:\Programming\Courses\Fullstack-Helsinki-2020\mongo_testing\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:20)
    at listOnTimeout (internal/timers.js:554:17)
    at processTimers (internal/timers.js:497:7)
(node:18284) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:18284) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:18284) DeprecationWarning: Listening to events on the Db class has been deprecated and will be removed in the next major version.

我当前的 Mongoose 和 MongoDB 版本(来自 package.json):

"mongoose": {
      "version": "5.11.16",
      "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.11.16.tgz",
      "integrity": "sha512-qmolyGAskPuq0Xr3j2Tjm9jwRccGGnLRWtTuyRvYBZoyItajwIoQdetJH8oVzs3N7aZK/GKZ82xV/t97suF8Pg==",
      "requires": {
        "@types/mongodb": "^3.5.27",
        "bson": "^1.1.4",
        "kareem": "2.3.2",
        "mongodb": "3.6.4",
        "mongoose-legacy-pluralize": "1.0.2",
        "mpath": "0.8.3",
        "mquery": "3.2.4",
        "ms": "2.1.2",
        "regexp-clone": "1.0.0",
        "safe-buffer": "5.2.1",
        "sift": "7.0.1",
        "sliced": "1.0.1"
      },
      "dependencies": {
        "mongodb": {
          "version": "3.6.4",
          "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.6.4.tgz",
          "integrity": "sha512-Y+Ki9iXE9jI+n9bVtbTOOdK0B95d6wVGSucwtBkvQ+HIvVdTCfpVRp01FDC24uhC/Q2WXQ8Lpq3/zwtB5Op9Qw==",
          "requires": {
            "bl": "^2.2.1",
            "bson": "^1.1.4",
            "denque": "^1.4.1",
            "require_optional": "^1.0.1",
            "safe-buffer": "^5.1.2",
            "saslprep": "^1.0.0"
          }
        },
        "safe-buffer": {
          "version": "5.2.1",
          "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
          "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="
        }
      }
    

问题:为什么上面的例子会引发上面的错误,一般来说,为什么我的 Mongoose 请求都超时了?

【问题讨论】:

  • 为什么不等待建立连接?在mongoose.connect 之后添加.then.catch。在.then发送请求。
  • 我刚刚编辑了我的代码并尝试了,它给了我同样的错误。如果您发布有效的解决方案,我会接受它作为答案。

标签: node.js mongodb mongoose dependencies timeout


【解决方案1】:

首先您需要等待建立连接以确保它会正常,请参阅Error handling

try {
  await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
} catch (error) {
  handleError(error);
}

save呼叫将被解决或被拒绝之后,您需要再次呼叫mongoose.connection.close()

exampleOne.save().then(res => {
  console.log(res)
  mongoose.connection.close()
})

因为您没有使用await,所以save 调用没有等待解析,而立即调用了mongoose.connection.close()

const res = await exampleOne.save()
console.log(res)
mongoose.connection.close()
})

【讨论】:

    【解决方案2】:

    正如我在评论中所说,@Anatoly 也说过你应该在建立连接后发送请求(即保存)。

    const mongoose = require('mongoose')
    
    const exampleSchema = new mongoose.Schema({
      title: String,
      author: String
    })
    
    const Example = mongoose.model('Example', exampleSchema)
    
    const mongoURL = //replace this comment with your own Mongo URL
    
    mongoose.connect(mongoURL, { 
      useNewUrlParser: true, 
      useUnifiedTopology: true, 
      useFindAndModify: false, 
      useCreateIndex: true 
    })
    .then(() => {
      const exampleOne = new Example({
        title: 'Don Quixote',
        author: 'M. Cervantes'
      })
    
      exampleOne.save().then(res => {
        console.log(res)
        mongoose.connection.close()
      })
    })
    .catch(err => {
      // handle error
    })
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多