POST登录请求报错:`users.findOne()` buffering timed out after 10000ms问题排查求助
Hey there, let's break down why you're hitting that users.findOne() timeout error and fix it step by step.
Root Cause Analysis
The biggest clue is in your Heroku logs: you see Connected to Mongo Successfully! after the login request comes in. That means your app is only initiating the MongoDB connection when it receives the first request, not when the server starts up. By the time the User.findOne() query runs, the database connection isn't fully ready yet, so the operation times out after 10 seconds.
Step-by-Step Fixes
1. Initialize MongoDB Connection Before Starting Your Server
Move your MongoDB connection logic to the very top of your entry file (like index.js) and wait for it to succeed before launching the Express server. This ensures your app only accepts requests once the database is fully connected.
Here's the corrected structure:
const mongoose = require('mongoose'); const express = require('express'); const app = express(); // MongoDB connection FIRST – don't skip this! const mongoURI = process.env.MONGODB_URI; // Use Heroku env var for production mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('Connected to Mongo Successfully!'); // Start server ONLY after connection is confirmed const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`my-notebook backend listening at http://localhost:${PORT}`); }); }) .catch(err => { console.error('Failed to connect to Mongo:', err.message); process.exit(1); // Exit if connection fails – no point running without DB }); // Load middleware and routes AFTER connection setup app.use(express.json()); app.use('/api/auth', require('./routes/auth')); // ... add other routes here
2. Fix the Frontend Fetch URL Typo
In your LoginPage.js, there's an extra colon in the API URL that could cause unexpected request issues:
// Original (broken) URL fetch(`https://my-notebook-mohit.herokuapp.com:/api/auth/login`);
Remove the extra colon to fix it:
// Corrected URL fetch(`https://my-notebook-mohit.herokuapp.com/api/auth/login`);
3. Verify Heroku Environment Variables
Double-check your Heroku app's config vars (Dashboard > Your App > Settings > Config Vars) to ensure your MONGODB_URI is valid. Make sure it includes the correct username, password, cluster address, and database name – a typo here is a common cause of connection timeouts.
4. Add Connection Error Monitoring
Add listeners to catch unexpected MongoDB connection drops after startup:
mongoose.connection.on('error', err => { console.error('MongoDB connection lost:', err); });
This will help you debug if the connection drops later, causing repeat timeouts.
5. Confirm Your User Model Collection Name
Your User model uses mongoose.model("users", UserSchema) – Mongoose automatically pluralizes model names, but just confirm your MongoDB collection is named users (or let Mongoose create it if it doesn't exist). If you intended a different collection name, adjust the model argument accordingly.
Final Steps
Redeploy your backend to Heroku and frontend to Netlify after making these changes. The timeout error should disappear once your server waits for the MongoDB connection to be ready before handling requests.
内容的提问来源于stack exchange,提问作者MagnusEffect

