Search code examples
javascriptnode.jsmongodbmongoosedotenv

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


I am trying to get results from a non-existing database at Mongodb Atlas. I was expecting a null value, instead I am getting a timeout error.

connect-db.js:

import { connect } from "mongoose";
import "dotenv/config";

const connectDb = async () => {
    try {
        const conn = await connect(`${process.env.MONGO_URI}/discord`);
        console.log(`Mongo db connected: ${conn.connection.host}`);
    } catch (error) {
        console.log(error);
        process.exit(1);
    }
};

connectDb();

schema and model

import { model, Schema } from "mongoose";

const BirthdaySchema = new Schema({
    discordID: String,
    birth_date: String,
});

const BirthdayModel = model("birthday", BirthdaySchema);

export default BirthdayModel;

get_birthday.js:

import BirthdayModel from "../models/birthday_model.js";

export const getBirthday = async (id) => {
    try {
        const getData = await BirthdayModel.exists({ discordID: id });
        if (!getData) {
            return null;
        }
        console.log(getData);
        return getData;
    } catch (error) {
        throw new Error(error);
    }
};

Finally, the error:

Error: MongooseError: Operation `birthdays.findOne()` buffering timed out after 10000ms
    at getBirthday (file:///home/xxxx/Documents/xxxx/modules/get_birthday.js:12:15)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.execute (file:///home/xxxx/Documents/xxxx/commands/set_birthday.js:26:25)
    at async Object.execute (file:///home/xxxx/Documents/xxxx/events/interaction.js:17:13)
node:events:492
      throw er; // Unhandled 'error' event

I checked that the connection being established so there is no problem with regard to connection. Is it because of the non-existent database? How should I resolve this if there's no predefined collection before using find or exists methods?


Solution

  • I am really dumb, I just resolved this a few moments ago. All this time I was separately initiating the connection to Atlas (connect_db.js) and running the event get_birthday.js separately. I just had to put connectDb() in the main index.js file for it to work.

    I didn't know initiating them separately would be a problem and I still don't understand why it is a problem.