MongooseError:操作“featureds.find()”缓冲在 10000 毫秒后超时

时间:2020-12-23 02:22:38

标签: javascript node.js mongodb mongoose

我在 MongoDB 上有一个集合,我正在尝试使用 find() 从中查询所有元素:

const mongoose = require('mongoose');
const Featured = mongoose.model('featured');
module.exports = app => {
    app.get('/api/featured', async (req, res) => {
      console.log("featured route");
      const featured = await Featured.find();
      console.log(featured);
      res.send(featured);
    })
}

这是 Featured.js:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const featuredSchema = new Schema({});

mongoose.model('featured', featuredSchema);

但是,我在提出请求时遇到错误:

(node:75568) UnhandledPromiseRejectionWarning: MongooseError: Operation `featureds.find()` buffering timed out after 10000ms
    at Timeout.<anonymous> (/Users/prikshetsharma/Desktop/humboiserver/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:184:20)
    at listOnTimeout (internal/timers.js:554:17)
    at processTimers (internal/timers.js:497:7)
(node:75568) 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: 2)

如何修复此错误并使所有集合项以 find() 返回?奇怪的是,错误显示 featureds.find() 而我从来没有在我的代码中的任何地方使用过特色词。

2 个答案:

答案 0 :(得分:0)

快速修复:

  • Featured.js 中导出模型:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const featuredSchema = new Schema({}, { collection: "featured" });
module.exports = mongoose.model('featured', featuredSchema);

UnhandledPromiseRejectionWarning:未处理的承诺拒绝,

  • 您需要将服务代码包装在 try catch 块中,
const mongoose = require('mongoose');
// correct this path to your original path of Featured.js
const Featured = require('./Featured.js');
app.get('/api/featured', async (req, res) => {
  try {
    console.log("featured route");
    const featured = await Featured.find();
    console.log(featured);
    res.send(featured);
  }
  catch(e) {
    console.log('Catch an error: ', e)
  } 
});

featureds.find() 缓冲在 10000 毫秒后超时,

  • 有很多可能性,
  1. 从 node_module 和 *.json 文件中删除 mongoose 模块,重新安装 mongoose 模块并重试。
  2. 检查您是否已连接数据库,然后检查您是否对数据库集群具有正确的网络访问权限。

答案 1 :(得分:0)

对于可能偶然发现此问题的其他任何人:我的问题与错误连接有关,我设法通过使用 mongoose.connect 而不是 mongoose.createConnection 来修复它。

请注意Mongoose documentation saying

<块引用>

默认情况下,如果您使用没有连接的模型,Mongoose 不会抛出任何错误。

...这只会导致缓冲超时。