如何解决 Mongoose v5.11.0 model.find() 错误:操作`products.find()` 缓冲在 10000 毫秒后超时"

nel*_*nym 8 mongoose

如何解决model.find() 函数产生“... ms 后缓冲超时”的问题?我正在使用 mongoose v 5.11.0、npm v6.14.8 和 mongodb v

这是代码。

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const assert = require('assert');

var mongoose = require('mongoose');

try {
    var db = mongoose.connect('mongodb://localhost:27017', {useNewUrlParser: true, dbName: 'swag-shop' });
    console.log('success connection');
}
catch (error) {
    console.log('Error connection: ' + error);
}


var Product = require('./model/product');
var WishList = require('./model/wishlist');

//Allow all requests from all domains & localhost
app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "POST, GET");
  next();
});

app.get('/product', function(request, response) {

    Product.find({},function(err, products) {
        if (err) {
            response.status(500).send({error: "Could not fetch products. "+ err});
        } else {
            response.send(products);
        }
    });
});

app.listen(3004, function() {
    console.log("Swag Shop API running on port 3004...");
});
Run Code Online (Sandbox Code Playgroud)

产品型号:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var product = new Schema({
    title: String,
    price: Number,
    likes: {type: Number, default: 0}
});

module.exports = mongoose.model('Product', product);
Run Code Online (Sandbox Code Playgroud)

此外,运行该文件还会产生以下警告:

D:\Test\swag-shop-api>nodemon server.js
[nodemon] 2.0.6
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
success connection
Swag Shop API running on port 3004...
(node:28596) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type function ([Function (anonymous)])
    at validateString (internal/validators.js:122:11)
    at Url.parse (url.js:159:3)
    at Object.urlParse [as parse] (url.js:154:13)
    at module.exports (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\url_parser.js:15:23)
    at connect (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:403:16)
    at D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:217:7
    at new Promise (<anonymous>)
    at MongoClient.connect (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:213:12)
    at D:\Test\swag-shop-api\node_modules\mongoose\lib\connection.js:820:12
    at new Promise (<anonymous>)
    at NativeConnection.Connection.openUri (D:\Test\swag-shop-api\node_modules\mongoose\lib\connection.js:817:19)
    at D:\Test\swag-shop-api\node_modules\mongoose\lib\index.js:345:10
    at D:\Test\swag-shop-api\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:5
    at new Promise (<anonymous>)
    at promiseOrCallback (D:\Test\swag-shop-api\node_modules\mongoose\lib\helpers\promiseOrCallback.js:30:10)
    at Mongoose._promiseOrCallback (D:\Test\swag-shop-api\node_modules\mongoose\lib\index.js:1135:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:28596) 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:28596) [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.
Run Code Online (Sandbox Code Playgroud)

我尝试增加bufferTimeoutMS或禁用bufferCommands,但仍然无法正常工作。

Naf*_*fis 15

根据此链接中的文档:https : //mongoosejs.com/docs/connections.html#buffering

Mongoose 让您可以立即开始使用您的模型,而无需等待 mongoose 与 MongoDB 建立连接。

那是因为猫鼬在内部缓冲模型函数调用。这种缓冲很方便,但也是一个常见的混淆源。如果您在没有连接的情况下使用模型,Mongoose 默认不会抛出任何错误。

特尔;博士:

您的模型在建立连接之前被调用。您需要将async/await与 connect() 或 createConnection() 一起使用;或者使用.then(),因为这些函数现在从Mongoose 5返回承诺。


nel*_*nym 7

通过删除文件夹、文件并重新安装模块解决了model.find() error: Operation products.find() buffering timed out after 10000ms"该问题。node_module*.jsonmongoose

按照此说明解决了警告问题https://mongoosejs.com/docs/deprecations.html


Sau*_*rav 7

嗯,我遇到了同样的问题并且有非常相似的代码。我在测试时发送 get 请求时遇到了同样的错误。

最终,我找到了解决方案,即我的本地主机数据库当时没有运行。虽然这是一个愚蠢的错误,但我很难找到它。

  • 在看到这个答案之前,我也很难找到错误。 (3认同)

小智 5

出现此错误是因为您在创建与数据库的连接之前尝试访问模型

始终在 app.js 中链接您的 mongodbconnection 文件(如果您已创建)

 var mongoose = require('./mongoconnection');
Run Code Online (Sandbox Code Playgroud)

或者只是将 mongodb 连接代码保留在 app.js 中


小智 5

对我来说是 100% MongoDB Atlas 问题。我在圣保罗创建了一个集群,但由于某种原因未能按预期工作。我已将其删除,并在 AWS/弗吉尼亚北部 (us-east-1) 创建一个新的,然后一切又开始工作。

我正在使用这个函数连接到数据库并避免一些警告

mongoose.connect(
    url,
    { useNewUrlParser: true, useUnifiedTopology: true },
    function (err, res) {
        try {
            console.log('Connected to Database');
        } catch (err) {
            throw err;
        }
    });
Run Code Online (Sandbox Code Playgroud)

  • 不再需要 `{ useNewUrlParser: true, useUnifiedTopology: true }` (2认同)

Moh*_*eid 5

只需使用127.0.0.1而不是localhost

mongoose.connect('mongodb://127.0.0.1:27017/myapp');
Run Code Online (Sandbox Code Playgroud)

或者在 mongoose.connect 方法中使用 family:4

mongoose.connect('mongodb://localhost:27017/TESTdb', {
    family:4
})
    .then(() => {
        console.log('FINE');
    })
    .catch(() => {
        console.log("BAD");
    })
Run Code Online (Sandbox Code Playgroud)

  • 如果我在真实的 Mongo 集群上遇到错误,这有什么帮助? (2认同)