I am working on a Next.js application where I need to query a MongoDB database using Mongoose. Despite ensuring the MongoDB connection is established, my queries keep timing out with the error: Operation places.find() buffering timed out after 10000ms.
Place.js
import mongoose from 'mongoose';
const placeSchema = new mongoose.Schema({
country: String,
population: Number,
work: {
pub: Number,
pub_ratio: Number,
languages: {
primary: String,
secondary: String,
},
avg: Number,
attendance: Number,
},
culture: {
food_type: String,
climate: String,
internet_penetration: String,
transportation_infra: String,
crime_rate: String,
recreation: String,
},
});
placeSchema.index({ 'culture.recreation': 1 });
const Place = mongoose.models.Place || mongoose.model('Place', placeSchema, 'places');
export default Place;
connectDB.js
import mongoose from 'mongoose';
const MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost:27017/NG_DESTINATION';
if (!MONGO_URI) {
throw new Error('Please define the MONGO_URI environment variable inside .env.local');
}
let cached = global.mongoose;
if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}
async function connectDB() {
console.log('Checking cached connection...');
if (cached.conn) {
console.log('Using cached connection');
return cached.conn;
}
if (!cached.promise) {
console.log('No cached promise found, creating new connection promise...');
const opts = {
bufferCommands: false,
serverSelectionTimeoutMS: 50000,
socketTimeoutMS: 50000,
};
cached.promise = mongoose.connect(MONGO_URI, opts).then((mongoose) => {
console.log('MongoDB connected');
return mongoose;
}).catch(err => {
console.error('MongoDB connection error:', err);
throw err;
});
}
try {
cached.conn = await cached.promise;
console.log('MongoDB connection established');
} catch (error) {
console.error('Error awaiting connection promise:', error);
throw error;
}
return cached.conn;
}
export default connectDB;
match-places.js
import connectDB from '../../../lib/connectDB';
import Place from '../../../backend/models/Place';
export default async (req, res) => {
if (req.method === 'POST') {
try {
console.log("Connecting to database...");
await connectDB();
console.log("Connected to database");
const userPreferences = req.body;
console.log("User Preferences: ", userPreferences);
console.log("Starting MongoDB query...");
const places = await Place.find({}).limit(10);
console.log("Places found: ", places);
if (places.length === 0) {
console.error("No places found.");
return res.status(404).json({ error: "No places found." });
}
res.status(200).json({ places });
} catch (error) {
console.error("Error during database operation: ", error);
res.status(500).json({ error: error.message });
}
} else {
res.status(405).end(); // Method Not Allowed
}
};
index.js
import React, { useState } from 'react';
import { Box, ChakraProvider, Text } from '@chakra-ui/react';
import axios from 'axios';
import Questionnaire from '../../components/Questionnaire';
import Results from '../../components/Results';
const Home = () => {
const [place, setPlace] = useState(null);
const handleSubmit = async (responses) => {
try {
console.log("Home - Submitting Responses:", responses);
const response = await axios.post('/api/match-places', responses);
console.log("Home - API Response:", response.data);
setPlace(response.data.recommendation);
} catch (error) {
console.error('Error fetching recommendation:', error);
}
};
return (
<ChakraProvider>
<Box p={5}>
<Text fontSize="3xl" fontWeight="bold">Find Your Destination</Text>
<Questionnaire onSubmit={handleSubmit} />
{place && <Results place={place} />}
</Box>
</ChakraProvider>
);
};
export default Home;
Issue Description
- When submitting the form in the front end, I encounter the following error:
POST http://localhost:3000/api/match-places 500 (Internal Server Error)
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', ...}
-
It seems to always fail on this line:
const places = await Place.find({}).limit(10);
-
The server logs show:
Error during database operation: MongooseError: Operation `places.find()` buffering timed out after 10000ms
What I tried
- Ensured Connection is Established Before Querying:
- Used async/await to ensure the connection is established before performing queries.Verified MongoDB Server is Running:
- Checked MongoDB server status using sudo systemctl status mongod.
- Connected to MongoDB using the MongoDB shell and verified that queries work fine:
mongosh
use NG_DESTINATION
db.places.find().limit(1)
- Tested Database Connection with a Standalone Script:
- Created and ran a standalone script (testConnectionDB.js) which connects to the database and performs a query successfully:
const mongoose = require('mongoose');
const MONGO_URI = 'mongodb://localhost:27017/NG_DESTINATION';
const placeSchema = new mongoose.Schema({
country: String,
population: Number,
work: {
pub: Number,
pub_ratio: Number,
languages: {
primary: String,
secondary: String,
},
avg: Number,
attendance: Number,
},
culture: {
food_type: String,
climate: String,
internet_penetration: String,
transportation_infra: String,
crime_rate: String,
recreation: String,
},
});
const Place = mongoose.model('Place', placeSchema, 'places');
async function testConnection() {
try {
await mongoose.connect(MONGO_URI);
console.log('MongoDB connected');
const places = await Place.find({ 'culture.recreation': 'Soccer' });
console.log('Places found:', places);
mongoose.connection.close();
} catch (error) {
console.error('Error connecting to MongoDB:', error);
}
}
testConnection();
Expectation
- It should return the matching data to the screen from my local MongoDB database where:
'culture.recreation' = 'soccer'