Next.js API Route Timing Out with Mongoose Query: Operation places.find() buffering timed out after 10000ms

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

  1. Ensured Connection is Established Before Querying:
  • Used async/await to ensure the connection is established before performing queries.Verified MongoDB Server is Running:
  1. 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)
  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'

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật