I’m working on a todo list project with nextjs 14, and when I created the project, it was working fine. All CRUD functions working well. I’m new on nextJs and backend work. Now I want to work again on my project, but I can’t connect to my db. I’m facing this issue:
MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you’re trying to access the database from an IP that isn’t whitelisted. Make sure your current IP address is on your Atlas cluster’s IP whitelist: https://www.mongodb.com/docs/atlas/security-whitelist/
I’ve deleted and added again my Ip address in the Network Access, and I’ve allowed access from anywhere. ButI’m still facing the same issue, everything I tried to fix this issue, doesn’t fix it
Here is my code so you could have a better view to my issue:
— db.js —
import mongoose from 'mongoose';
export const connect = async () => {
try {
mongoose.connect(process.env.MONGO_URI)
mongoose.connection.on('connected', () => {
console.log("Connected to database")
})
} catch (error) {
console.log("Faileed to connect to database", error)
}
}
— model.js —
import mongoose from "mongoose";
const TodoSchema = new mongoose.Schema({
id: {
type: String,
required: true,
unique: true
},
desc: {
type: String,
required: true
},
completed: {
type: Boolean,
default: false
},
category: {
type: String,
required: true
},
priority: {
type: String,
required: true
}
})
const Todo = mongoose.models.todos || mongoose.model('todos', TodoSchema);
export default Todo;
— route.ts —
import { NextRequest, NextResponse } from "next/server";
import { connect } from "@/dbConfig/db";
import Todo from "@/models/Todo";
import { v4 as uuidv4 } from "uuid";
connect();
export const GET = async (request: NextRequest) => {
try {
const todos = await Todo.find({});
console.log(todos);
return NextResponse.json({
msg: "Founded all todos",
success: true,
todos,
});
} catch (error) {
console.error("Error fetching todos:", error)
return NextResponse.json({ msg: `Issue happened, ${error}` }, { status: 500 });
}
};
export const POST = async (request: NextRequest) => {
try {
const reqBody = await request.json();
const { desc } = reqBody;
console.log(desc);
const newTodo = new Todo({
id: uuidv4(),
desc,
completed: false,
});
const savedTodo = await newTodo.save();
return NextResponse.json({
msg: "Todo created",
success: true,
savedTodo,
});
} catch (error) {
return NextResponse.json({ msg: "Issue happened" }, { status: 500 });
}
};
export const DELETE = async (request: NextRequest) => {
try {
await Todo.deleteMany({})
return NextResponse.json({
msg: "Todos cleared",
success: true,
});
} catch (error) {
return NextResponse.json({ msg: "Issue happened" }, { status: 500 });
}
}`
I’m trying to access my db, and be able to get my todos, edit them, clear them all or edit them