简体   繁体   中英

Why are all my Mongoose requests timing out?

My Mongoose requests have all been timing out since yesterday.

My internet connection is working well, the same as usual, and my source code is unchanged.

So, I think it must be a problem with my dependencies or with MongoDB itself.

Minimal reproducible example:

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

Full error trace from running the above example:

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

My current Mongoose and MongoDB versions (from 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=="
        }
      }
    

Question: Why is the above example raising the above error, and, in general, why have my Mongoose requests all been timing out?

First you need to wait a connection to be established to make sure it will be ok, see Error handling :

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

Second you need to call mongoose.connection.close() after save call will be either resolved or rejected:

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

because you didn't use await the save call didn't wait for resolve and mongoose.connection.close() was immediately called.

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

As I said in comment and also @Anatoly said you should send request (ie save) after that connection was established.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM