Node.js使用Mongoose连接MongoDB超时问题求助
解决Mongoose操作缓冲超时问题:Operation
fruits.insertOne() buffering timed out after 10000ms 错误原因
你遇到的超时问题核心是数据操作在数据库连接建立前就执行了:main()是异步函数,虽然内部用await等待连接,但main()之后的fruit.save()不会等待连接完成就直接运行,此时Mongoose还未建立数据库连接,只能将操作放入缓冲队列,超时后触发错误。
另外你同时混用了Mongoose API和原生MongoDB API(findDocuments函数),这会增加代码复杂度,建议统一使用Mongoose的方法。
修正方案
将所有数据库操作(创建文档、查询数据等)放入main()函数内部,确保在连接成功后执行,同时统一使用Mongoose API:
const mongoose = require('mongoose'); async function main() { try { // 等待数据库连接成功 await mongoose.connect('mongodb://localhost:27017/fruitsDB'); console.log('数据库连接成功'); // 定义Schema与Model const fruitSchema = new mongoose.Schema({ name: String, rating: Number, review: String }); const Fruit = mongoose.model("Fruit", fruitSchema); // 创建并保存文档 const fruit = new Fruit({ name: "Apple", rating: 7, review: "Great!" }); await fruit.save(); console.log('水果数据已保存'); // 使用Mongoose查询所有文档 const fruits = await Fruit.find({}); console.log("查询到的记录:"); console.log(fruits); } catch (err) { console.error('数据库操作失败:', err); } finally { // 可选:操作完成后关闭连接 await mongoose.connection.close(); } } // 启动主流程 main();
额外排查点
- 确认MongoDB服务确实在
localhost:27017运行,可通过mongosh mongodb://localhost:27017命令测试连接 - 若使用MongoDB 6.0+版本,可尝试在连接字符串添加
?directConnection=true解决网络配置问题:await mongoose.connect('mongodb://localhost:27017/fruitsDB?directConnection=true');
内容的提问来源于stack exchange,提问作者Azad Raj
相关产品推荐
相关产品推荐

