Here is a code snippet attempting to connect to a MongoDB using Mongoose: file: app/utils/db.ts
import connect from "@/app/utils/db.ts";
import * as dotenv from 'dotenv'
import * as mongoose from "mongoose";
import endpointsConfig from '@/endpoints.config';
dotenv.config();
const uri = endpointsConfig.mongoUri?.toString() ?? ''
console.log("pre uri log")
console.log(uri)
console.log("post uri log")
const connect = async () => {
try {
console.log("inside try")
await mongoose.connect("mongodb+srv://mooddb:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eabc8da2b9ddbe84a8bb87dd8f8289a4aa8785858ec7988f8985988e8f98c48f809880d3808bc48785848d858e88c4848f9e">[email protected]</a>/test?retryWrites=true&w=majority");
} catch (error) {
console.log("inside catch")
throw new Error("Connection failed!");
}
};
export default connect;
This is the API where I want to use the MongoDB connection with a simple test to verify if it works: file: app/api/auth/register.ts
import connect from "@/app/utils/db";
import { NextResponse } from "next/server";
export const POST = async (req : any) =>{
const {test} = await req.json();
await connect(); //I believe this is the line causing issues
return new NextResponse(test)
}
Here is where the API is called:
app/components/RegistrationForm.tsx
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
event.stopPropagation();
// Further validation or form data submission can be implemented here
console.log(formData);
if (
formData.email === formData.confirmEmail &&
formData.password == formData.confirmPassword
) {
try {
const res = await fetch("/api/auth/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
formData,
}),
});
res.status === 201;
console.log("fetch sent");
} catch (err: any) {
setError(err);
console.log(err);
}
}
};
The code above represents the submit handler of a registration form, which is currently being tested to debug and fix errors.
Upon compiling the form and triggering the submitHandler, the following error is encountered:
Error during SSR Rendering
...
Cannot set properties of undefined
...
[500] /api/auth/register (522ms)
The technology stack being used includes:
- Next.js 13.4.7
- TypeScript 5.1.3
- Node.js 19.8.1
- Mongoose 7.3.1
Turbopack is also being utilized in the project.
The primary goal is to establish a database connection and successfully register a new user, but the ongoing issue relates to the mongoose connection failing consistently.