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

如何解决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...");
});

产品型号:

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

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

D:Testswag-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:Testswag-shop-apinode_modulesmongoosenode_modulesmongodbliburl_parser.js:15:23)
    at connect (D:Testswag-shop-apinode_modulesmongoosenode_modulesmongodblibmongo_client.js:403:16)
    at D:Testswag-shop-apinode_modulesmongoosenode_modulesmongodblibmongo_client.js:217:7
    at new Promise (<anonymous>)
    at MongoClient.connect (D:Testswag-shop-apinode_modulesmongoosenode_modulesmongodblibmongo_client.js:213:12)
    at D:Testswag-shop-apinode_modulesmongooselibconnection.js:820:12
    at new Promise (<anonymous>)
    at NativeConnection.Connection.openUri (D:Testswag-shop-apinode_modulesmongooselibconnection.js:817:19)
    at D:Testswag-shop-apinode_modulesmongooselibindex.js:345:10
    at D:Testswag-shop-apinode_modulesmongooselibhelperspromiseOrCallback.js:31:5
    at new Promise (<anonymous>)
    at promiseOrCallback (D:Testswag-shop-apinode_modulesmongooselibhelperspromiseOrCallback.js:30:10)
    at Mongoose._promiseOrCallback (D:Testswag-shop-apinode_modulesmongooselibindex.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.

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

回答

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

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

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

特尔;博士:

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


以上是如何解决Mongoosev5.11.0model.find()错误:操作`products.find()`缓冲在10000毫秒后超时"的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>