Running into issues while trying to establish a connection to MongoDB using Mongoose in a NextJS Typescript environment. Getting

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.

Answer №1

During my experience with Next.js, I faced a similar problem using version 14.0.4. Fortunately, the issue was resolved after I upgraded to version 14.1.0, and I did not encounter it again.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering the "Error: Promise { <pending> }" message when trying to execute the "Log.save();" function in MongoDB

https://i.sstatic.net/CVuar.png I encountered an error while following the MongoDB Atlas Blog tutorial to input information into MongoDB. Despite attempting to troubleshoot and seek solutions, the error persists. Below is my connection file: async functi ...

Encountering unanticipated breakpoints in compiled .Next files while using Visual Studio Code

As a newcomer to NextJS, I have encountered an issue that is disrupting my workflow. I followed the instructions in https://nextjs.org/docs/advanced-features/debugging#using-the-debugger-in-visual-studio-code to set up my launch.json file. Although I am ...

Solve problems with connecting to mongodb during initialization

I have successfully integrated MongoDB using Spring and my data service includes an autowired mongo repository. Everything runs smoothly except when the database is unavailable during startup. When MongoDB is down while the service initializes, an excepti ...

Sending binary information from a .net core web api to a typescript application

I currently have a .net core 3.0 web api application connected to an angular 8 client. While I have successfully transferred data between them using json serialization, I am now looking for a way to transfer a bytes array from the api to the client. After ...

Tips for modifying array elements in MongoDB

I have some data stored in a mongoDB database that appears as follows { "_id": ObjectId("57c40e405e62b1f02c445ccc"), "sharedPersonId": ObjectId("570dec75cf30bf4c09679deb"), "notificationDetails": [ { "userId": "57443657ee5b5ccc30c4e6f8", ...

The type '(props: Props) => Element' cannot be assigned to the type 'FunctionComponent<FieldRenderProps<any, HTMLElement>>' in React-final-form

I'm fairly new to using TypeScript, and I am currently working on developing a signUp form with the help of React-Final-Form along with TypeScript. Here is the code snippet that describes my form: import React from "react"; import Button from "@mater ...

Linear gradient background issue not functioning properly when transitioning between screens using Next.js

Encountered an unusual issue with Next.js. My background linear gradients are not loading properly when navigating between pages. The link in question is: import Link from 'next/link' <Link href='/register'> <a> click m ...

Tips for transforming TypeScript Enum properties into their corresponding values and vice versa

Situation Imagine having an enum with string values like this: enum Fruit { Apple = "apple", Orange = "orange", Banana = "banana", Pear = "pear" } Users always input a specific string value ("apple", "banana", "orange", "pear") from a drop-down li ...

How to properly cast interfaces when using Angular 4's HttpClient to fetch items

Here is the layout of my interface interface IPlacesResult { summary: { queryTime: number; // ... }; results: { id: string; // ... address: { streetNumber: number; // ... }; }[]; } To populate this interface, I ...

Inquiring about the syntax of TypeScript and React – any insights?

Hello! I am currently delving into the world of React and Typescript, and I have a query regarding syntax interpretation. Let's say I have a segment of code from test.tsx shown below. // prop is defined somewhere over here. private displa ...

Working with referenced MongoDB records using the _id field

Currently, I have a basic setup in my MEAN app (which consists of node, mongoose, and mongo) where I organize Book records and User records. A Book is linked to a single Owner and can be shared with multiple users whose details are saved in an array within ...

Oops! Looks like there's a type error in module "*.mdx" - it seems that it doesn't have the exported member "metadata". Maybe try using "import metadata from "*.mdx"" instead?

I am attempting to extract metadata from an mdx file. I have followed the guidelines outlined in NextJS Markdown Frontmatter, but encountered build errors. It is important to note that I am unable to utilize fs. Code Section Page.tsx File import Conte ...

When receiving JSON and attempting to store the data in a variable, I encounter an issue where it returns the error message "undefined is not iterable (cannot read property Symbol

I'm currently integrating the Advice Slip API into my project. I am experiencing an issue when trying to store the JSON data in a variable like so: let advice; fetch("https://api.adviceslip.com/advice").then(response => response.json()). ...

Encountering a Mongoose error during the upsert operation with findOneAndUpdate

While attempting to upsert using findOneAndUpdate, I encountered an error. ValidatedCertificates.findOneAndUpdate( //query { "course": req.body.course_name, "batch": req.body.batch_name }, { //update ...

What is the best way to trigger two functions simultaneously using an onClick event in NextJS?

I have defined two constants in my NextJs app, "toggleMenu" and "changeLanguage". When the language changer inside the menu is clicked, I want it to trigger both of these functions. However, I tried implementing this code but it doesn't seem to work ...

My NextJS application is experiencing issues with loading images in Firefox

The website is accessed through this URL. In my next.config.js file, I have the following code for cache policy: module.exports = { ... async headers() { return [ { source: '/:all*(svg|jpg|png|gif)', locale: false, ...

What is the best way to locate data using a function in Mongoose?

I have a database in mongodb using mongoose packages with the following data structure: [ { _id: new ObjectId("62ae97b6be08b688f93f2c07"), reportId: '1', method: 'A1', category: 'B2', date: &apos ...

Display tables side by side using Material-UI

Presently, I am utilizing NextJs and MaterialUI to display a table with data fetched from an API created in Strapi. Challenge The current issue lies in using a table component with props that are imported into a page, where the props are mapped to an API ...

Tips for inserting a JSON object within an embedded array object in MongoDB

I have the following document saved in my MongoDB database: { "_id": 2, "template_name": "AllahabadBank", "description": "Form For NewCustomer Application In Banking System", "handwritten": "true", "file_path": "./serverData/batchProce ...

What could be causing the malfunction of my token rotation feature in nextAuth?

I am developing a web application that involves working with an external API alongside my team member. We are making API requests using Next.js. I have implemented nextAuth for authentication, but I am facing issues with token rotation. After successful lo ...