User Registration With AuthJS Credentials and MongoDB
Unanswered
German yellowjacket posted this in #help-forum
German yellowjacketOP
I am trying to implement user registration and am wondering if I did this correctly and if I am doing the mongodb connection correctly since Ive heard something about keeping the connection open but not really sure what that means yet. If anyone can take a look and lmk I would appreciate it.
src > app > api > registerUser > route.ts
src > lib > mongodb.ts
src > app > api > registerUser > route.ts
import { connectToMongoDB } from "@/lib/mongodb";
import { NextResponse } from "next/server";
import User from "@/models/User";
export const POST = async (request: Request) => {
try {
const { name, email, password } = await request.json();
// Check if all fields are filled
if (!name || !email || !password) return NextResponse.json({ message: "Please fill in all fields." }, { status: 400 });
await connectToMongoDB();
// Check if user already exists
const userAlreadyExists = await User.findOne({ email });
if (userAlreadyExists) return NextResponse.json({ message: "User already exists." }, { status: 409 });
// Create new user
const newUser = new User({ name, email, password });
await newUser.save();
return NextResponse.json({ message: "User registered." }, { status: 201 });
}
catch (error) {
return NextResponse.json(
{ message: "Server error." },
{ status: 500 }
);
}
}src > lib > mongodb.ts
import mongoose from 'mongoose';
// MongoDB connection
export async function connectToMongoDB() {
try {
const mongoDBConnection = await mongoose.connect(String(process.env.MONGODB_URI))
console.log('MongoDB connected');
return mongoDBConnection;
}
catch (error) {
throw new Error('Error connecting to MongoDB: ' + error);
}
}