MongooseError: users.insertOne()缓冲超时10000ms的解决方案咨询
解决MongooseError: Operation
users.insertOne() buffering timed out after 10000ms错误 问题背景
遇到MongooseError: Operation users.insertOne() buffering timed out after 10000ms错误,已将数据库IP访问权限设置为允许所有访问,相关代码及终端输出如下:
Node.js代码
var express = require("express"); var bodyParser = require("body-parser"); var mongoose = require("mongoose"); const app = express(); app.use(bodyParser.json()); app.use(express.static("public")); app.use( bodyParser.urlencoded({ extended: true, }) ); mongoose.connect( "mongodb+srv://ab1:0000@ahmed.gqxyt3n.mongodb.net/ab.ac?retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology: true, } ); var db = mongoose.connection; db.on("error", () => console.log("Error in Connecting to Database")); db.once("open", () => console.log("Connected to Database")); app.post("/sign_up", (req, res) => { var name = req.body.name; var email = req.body.email; var phno = req.body.phno; var password = req.body.password; var data = { name: name, email: email, phno: phno, password: password, }; db.collection("users").insertOne(data, (err, collection) => { if (err) { throw err; } console.log("Record Inserted Successfully"); }); return res.redirect("signup_success.html"); }); app .get("/", (req, res) => { res.set({ "Allow-access-Allow-Origin": "*", }); return res.redirect("index.html"); }) .listen(3000); console.log("Listening on PORT 3000");
终端输出
PS C: \Users\ dream\ Desktop\ indea pro db > nodemon index.js[nodemon] 2.0 .19[nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): * .*[nodemon] watching extensions: js, mjs, json[nodemon] starting `node index.js` Listening on PORT 3000 C: \Users\ dream\ Desktop\ indea pro db\ index.js: 43 throw err; ^ MongooseError: Operation `users.insertOne()` buffering timed out after 10000 ms at Timeout. < anonymous > (C: \Users\ dream\ Desktop\ indea pro db\ node_modules\ mongoose\ lib\ drivers\ node - mongodb - native\ collection.js: 151: 23) at listOnTimeout(node: internal / timers: 559: 17) at processTimers(node: internal / timers: 502: 7)[nodemon] app crashed - waiting for file changes before starting...
解决方案
1. 等待数据库连接成功后再启动服务
原代码在数据库连接未完成时就启动了服务器,导致用户请求发送时连接还未建立,触发缓冲超时。需确保连接成功后再处理请求。
2. 验证连接字符串有效性
- 确认用户名、密码与MongoDB Atlas集群配置一致
- 检查数据库名(
ab.ac)是否合法,若集群中不存在该数据库,Mongoose会自动创建,但需确保集群权限允许 - 确认连接参数
retryWrites=true&w=majority符合集群要求
3. 使用Mongoose模型规范操作
Mongoose不推荐直接操作底层集合,定义Schema和Model更符合框架设计,能避免连接相关的隐性问题。
4. 完善错误日志与处理
原代码仅输出模糊的连接错误,需打印具体错误信息定位问题;同时在路由中正确捕获异步操作错误,避免服务崩溃。
修改后的示例代码
var express = require("express"); var bodyParser = require("body-parser"); var mongoose = require("mongoose"); const app = express(); // 中间件配置 app.use(bodyParser.json()); app.use(express.static("public")); app.use(bodyParser.urlencoded({ extended: true })); // 定义用户Schema与Model const userSchema = new mongoose.Schema({ name: String, email: String, phno: String, password: String }); const User = mongoose.model("User", userSchema); // 连接数据库并启动服务 mongoose.connect( "mongodb+srv://ab1:0000@ahmed.gqxyt3n.mongodb.net/ab.ac?retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology: true } ) .then(() => { console.log("Connected to Database"); // 连接成功后启动服务器 app.listen(3000, () => { console.log("Listening on PORT 3000"); }); }) .catch(err => { console.error("Database connection error:", err); }); // 注册接口 app.post("/sign_up", async (req, res) => { try { const userData = { name: req.body.name, email: req.body.email, phno: req.body.phno, password: req.body.password }; await User.create(userData); console.log("Record Inserted Successfully"); return res.redirect("signup_success.html"); } catch (err) { console.error("Insert error:", err); return res.status(500).send("Failed to create user"); } }); // 首页路由 app.get("/", (req, res) => { // 修复CORS头拼写错误 res.set({ "Access-Control-Allow-Origin": "*" }); return res.redirect("index.html"); });
修改说明
- 用
mongoose.connect()的Promise链式调用,确保连接成功后再启动服务器,避免请求提前触发 - 定义User模型,使用
User.create()替代直接操作集合,符合Mongoose最佳实践 - 修复CORS头的拼写错误(原代码为
Allow-access-Allow-Origin,正确应为Access-Control-Allow-Origin) - 使用
async/await处理异步插入操作,完善错误捕获与日志输出
内容的提问来源于stack exchange,提问作者THE GAME
相关产品推荐
相关产品推荐

