【发布时间】:2021-04-11 01:55:03
【问题描述】:
我正在尝试发出一个在 MongoDB 中保存查找数据的发布请求,或者如果它不存在则创建一个,然后我收到这样的错误
MongooseError: Operation `urls.find()` buffering timed out after 10000ms
我的 main.js
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use("/public", express.static(`${process.cwd()}/public`));
app.get("/", function (req, res) {
res.sendFile(process.cwd() + "/views/index.html");
});
// Your first API endpoint
app.get("/api/hello", function (req, res) {
res.json({ greeting: "hello API" });
});
app.listen(port, function () {
console.log(`Listening on port ${port}`);
});
mongoose.connect(
process.env.MONGODB_CONNECT,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
},
() => {
console.log("Connected to mongoDB");
}
);
let urlSchema = new mongoose.Schema({
original: { type: String, required: true },
short: Number,
});
let Url = mongoose.model("Url", urlSchema);
let responseObject = {};
app.post(
"/api/shorturl/new",
bodyParser.urlencoded({ extended: false }),
(request, response) => {
let inputUrl = request.body["url"];
responseObject["original_url"] = inputUrl;
let inputShort = 1;
Url.findOne({})
.sort({ short: "desc" })
.exec((error, result) => {
// THE ERROR APPEARS
console.log(error);
if (!error && result != undefined) {
inputShort = result.short + 1;
}
if (!error) {
Url.findOneAndUpdate(
{ original: inputUrl },
{ original: inputUrl, short: inputShort },
{ new: true, upsert: true },
(error, savedUrl) => {
if (!error) {
responseObject["short_url"] = savedUrl.short;
response.json(responseObject);
}
}
);
}
});
}
);
我的依赖
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.11.10"
我已经在类似的问题中尝试了一些解决方案,例如:
-
删除 node_module 文件并重新安装 mongoose
-
将MongoDB集群中nodejs的版本改为 2.2.12 或更高版本
-
将我的 IP 更改为 google 公共 DNS 8888 8844
任何帮助将不胜感激
【问题讨论】:
-
我试过了,没用
标签: node.js database mongodb mongoose mongodb-query