Node.js从MongoDB获取数据持续超时错误的排查求助
我正在搭建一个网站,前端使用React.js,后端使用Node.js,数据库采用MongoDB。我在数据库中存入了一些测试数据,使用Express和Mongoose进行开发,在Atlas上创建了数据库,数据库连接显示成功,但在浏览器访问localhost:5000/Companies获取集合数据时,始终返回连接超时错误。
我的代码文件:
server.js
const express=require('express') const { connectDB,disconnectDB } = require('./db'); const cors = require('cors'); const Company = require('./models/Company'); var app = express(); // Enable CORS for specific origins app.use(cors({ origin: 'http://localhost:3000' // Allow requests from http://localhost:3000 })); app.get("/api",(req,res)=>{ res.json({"users":["user1","user2", "user3"]}) }) app.get("/Companies",async (request,response)=>{ try { // Connect to MongoDB (if not already connected) await connectDB(); // Fetch all companies from the companies collection const companies = await Company.find(); // Send the list of companies as a JSON response response.json(companies); } catch (error) { // Handle errors console.error('Error fetching companies:', error); response.status(500).json({ error: 'Internal Server Error' }); } }) app.listen("5000",()=>{ console.log("Server is running on port 5000") }); // Handle graceful shutdown process.on('SIGINT', async () => { try { await disconnectDB(); console.log('Disconnected from MongoDB'); process.exit(0); } catch (error) { console.error('Error disconnecting from MongoDB:', error); process.exit(1); } });
models/Company.js
// models/Company.js const mongoose = require('mongoose'); // Define the schema for the Company collection const companySchema = new mongoose.Schema({ "_company_name": String, "_link": String // You can define other fields as needed }); // Create a Mongoose model for the Company collection const Company = mongoose.model('companies', companySchema); module.exports = Company;
db.js
// db.js const mongoose = require('mongoose'); require('dotenv').config(); const connectDB = async () => { try { await mongoose.connect('mongodb://localhost:27017/Zien', { }); console.log('db connection success'); } catch (error) { console.error('Error connecting to MongoDB:', error); } }; const disconnectDB = async () => { try { await mongoose.disconnect(); console.log('Disconnected from MongoDB'); } catch (error) { console.error('Error disconnecting from MongoDB:', error); } }; module.exports = { connectDB, disconnectDB };
已尝试的操作及错误:
- 切换本地MongoDB和Atlas连接字符串,均出现相同超时错误
- 使用
limit(10)减少单次获取的文档数量,仍无响应且超时,控制台报错:
Error fetching companies: MongooseError: Operation
companies.find()buffering timed out after 10000ms
at Timeout. (D:\backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23)
at listOnTimeout (node:internal/timers:573:17)
at process.processTimers (node:internal/timers:514:7)
- 尝试使用
toArray()转换查询结果,控制台报错:
Error fetching companies: TypeError: Company.find(...).limit(...).toArray is not a function
at D:\xampp\htdocs\employerrating\application\views\modules\zien-backend\server.js:33:56
解决方案
问题已解决,将connectDB调用移至app.listen的回调函数中,修改后的代码如下:
app.listen("5000",async ()=>{ try { await connectDB(); console.log("Server is running on port 5000") } catch (error) { console.error("Error starting server:", error); } });
问题原因是之前每次请求/Companies接口时都会尝试连接数据库,现在调整为服务器启动时就完成数据库连接,避免了重复连接导致的超时问题。
内容的提问来源于stack exchange,提问作者amalu

