Mongoose timeout issue on registering a new user to MongoDB (Nextjs app)

Implementing mongodb and the connection to mongodb through mongoshell showed it was ok.

I have a register function that imports a Mongoose schema which gives me this error:

MongooseError: Operation users.findOne() buffering timed out after 10000ms

Please help me resolve this. Thanks in advance!

// api/auth/register.js
import bcrypt from 'bcrypt'
import User from '@/models/User'
import { connectToDatabase } from '@/utils/mongodb'

export default async function handler(req, res) {
  
  await connectToDatabase() // no db object to destructure
  
  if (req.method === 'POST') {
    const { username, password } = req.body

    try {
      const existingUser = await User.findOne({ username })

      if (existingUser) {
        return res
          .status(400)
          .send({ success: false, message: 'Username already exists' })
      }

      const hashedPassword = await bcrypt.hash(password, 10)
      const newUser = await new User({ 
        username, 
        password: hashedPassword, 
        role: 'user' 
      }).save()

      return res.status(201).send({ success: true, data: newUser })
    } catch (error) {
      console.error(error)  // Log the error to console
      return res
        .status(500)
        .send({ success: false, message: 'Something went wrong', error: error.message })  // Send error message in response
    }
  } else {
    res.setHeader('Allow', ['POST'])
    return res
      .status(405)
      .send({ success: false, message: `Method ${req.method} not allowed` })
  }
}

// /models/User.js

import mongoose from 'mongoose'
import bcrypt from 'bcrypt'

const userSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  role: { type: String, default: 'user', enum: ['user', 'admin'] },
})

userSchema.pre('save', async function (next) {
  if (this.isModified('password')) {
    this.password = await bcrypt.hash(this.password, 10)
  }
  next()
})

export default mongoose.models.User || mongoose.model('User', userSchema)

// /utils/mongodb.js
import { MongoClient } from 'mongodb';

let cached = global.mongo;

if (!cached) cached = global.mongo = {};

export async function connectToDatabase() {
  if (cached.conn) return cached.conn;
  if (!cached.promise) {
    const opts = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      serverSelectionTimeoutMS: 30000 // Server selection timeout set to 30000ms
    };
    cached.promise = MongoClient.connect(process.env.MONGODB_URI, opts).then(
      (client) => {
        return { client, db: client.db(process.env.DB_NAME) };
      },
    );
  }
  cached.conn = await cached.promise;
  return cached.conn;
}

Hi @Alan_Wunsche,

Welcome to the MongoDB Community.

  • Can you please verify whether it was functioning correctly before? If it was, have there been any recent changes?

  • How are you currently testing the API? Could you share the specific error message from the log when executing the code?

  • Can the application code establish a connection to MongoDB? Is your IP address whitelisted?

  • Have you attempted testing a different API? Is the same error appearing there as well?

In case of further assistance, please provide details regarding the MongoDB version and the Mongoose version in use. It would also be helpful to include the error logs you’ve encountered.

Best regards,
Kushagra