I am trying to connect mongoDB with my nextjs (14) project through mongoose. But I am encountering problem with connecting mongoDB with nextjs (14).
It’s a simple nextjs form project to push email and username to my database and then read it to show those info.
When I try to submit data to my database it show’s this error …
MongooseError: Operation users.insertOne()
buffering timed out after 10000ms at Timeout. (D:\joy\nextJs\week nine\data-fetching\fetch-data\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:23) at listOnTimeout (node:internal/timers:573:17) at process.processTimers (node:internal/timers:514:7)
This is my connectMongo function to connect mongoDB with nextjs.
import mongoose from "mongoose";
const MONGO_URI = process.env.MONGO_URI;
const cached = {};
async function connectMongo() {
if (!MONGO_URI) {
throw new Error(
"Please define the MONGO_URI environment variable inside .env.local"
);
}
if (cached.connection) {
return cached.connection;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
};
cached.promise = mongoose.connect(MONGO_URI, opts);
}
try {
cached.connection = await cached.promise;
} catch (e) {
cached.promise = undefined;
throw e;
}
return cached.connection;
}
export default connectMongo;
This is UserShema model…
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema({
name: {
type: String,
default: "Anonymous",
min: 2,
max: 100,
},
email: {
type: String,
match: [
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
"Please fill a valid email address",
],
min: 2,
max: 100,
},
});
const User = mongoose.models.User || mongoose.model("User", UserSchema);
export default User;
and this is my form component…
import connectMongo from "@/dbConnect/connectMongo";
import User from "@/models/User";
export default function NewUserForm() {
const addUser = async (formData) => {
"use server";
const name = formData.get("name");
const email = formData.get("email");
const userData = {
name,
email,
};
try {
await connectMongo;
await new User(userData).save();
} catch (error) {
console.log(error);
}
};
return (
<form action={addUser}>
<div>
<input type='text' name='name' placeholder='Name' />
</div>
<div>
<input type='email' name='email' placeholder='Email' />
</div>
<div>
<button type='submit'>Submit</button>
</div>
</form>
);
}
point to be noted: I changed my local DNS to google DNS (8.8.8.8) and in mongoAtlas network access I allowed all user to access.