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

zen*_*vil 7 javascript mongoose mongodb node.js

我在 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);
    })
}

Run Code Online (Sandbox Code Playgroud)

这是Featured.js:

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

const featuredSchema = new Schema({});

mongoose.model('featured', featuredSchema);
Run Code Online (Sandbox Code Playgroud)

但是,我在发出请求时收到错误:

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

Run Code Online (Sandbox Code Playgroud)

如何修复此错误并让所有集合项目一起返回find()?奇怪的是,该错误显示featureds.find()我从未在代码中的任何地方使用过 features 一词。

tur*_*hal 0

快速修复:

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

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)
  } 
});
Run Code Online (Sandbox Code Playgroud)

featureds.find()10000ms后缓冲超时,

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