Mongoose and Next.js: Encountered Runtime Error - Cannot Access Undefined Properties (Token)

For some reason, the Model I defined is not working properly, despite being similar to another one that works without errors. Can anyone help me figure out why?

If you need to see a minimal, reproducible example, check it out here.

The problematic code:

import mongoose from 'mongoose';

const TokenSchema = new mongoose.Schema({
  _userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
  token: { type: String, required: true },
  createdAt: { type: Date, required: true, default: Date.now, expires: 43200 }
});

export default mongoose.models.Token || mongoose.model('Token', TokenSchema);

The working code:

import mongoose from 'mongoose';
import emailValidator from 'email-validator'
import bcrypt from 'bcrypt'

import crypto from 'crypto'

const SALT_ROUNDS = 12;

const UserSchema = new mongoose.Schema(
  {
    // Schema definition here
  },
  {
    timestamps: true
  }
);

// Methods and hooks definitions here

export default mongoose.models.User || mongoose.model('User', UserSchema)

I'm using this example from the Next.js repository as a reference.

Any assistance would be greatly appreciated!

Answer №1

It seems that the error

TypeError: Cannot read properties of undefined (reading 'Token')
is occurring because the code is running on the client side instead of the server side.

The issue is actually related to mongoose not establishing a connection to the database, resulting in mongoose.models being undefined. However, attempting to start a db connection is not the solution:

I encountered a similar problem when I attempted to define multiple entities in the same file. In my scenario, I was defining Typescript interfaces for client-side usage, causing the mongoose model definitions to run as well...

I learned that NextJS takes steps to separate code sent to the client and server sides. It's important for developers to separate client-side and server-side components into different files to avoid this issue.

In my situation, I organized Interface definitions and custom Hooks in one file, and Mongoose Schema definitions in another. By only importing what I needed, such as Interfaces and Hooks, I was able to resolve the errors.

While keeping everything together may seem logical, it's not effective in this context.

Answer №2

I implemented your code and it ran smoothly (it went into the tokens collection instead of token as expected) One observation I made was the presence of the expires field on createdAt - was this a NextJS feature? Since it's not a default field, I am just curious. Additionally, could you provide the exact error message you are facing? This information would be helpful in troubleshooting the issue.

{
  _userId: new ObjectId("5e1a0651741b255ddda996c4"),
  token: 'abcd123',
  createdAt: 2021-09-24T23:10:24.288Z,
  _id: new ObjectId("614e5ae04c741f91ac062530"),
  __v: 0
}

Furthermore, I suggest considering the use of the timestamps options property when defining the model. This will save you from the hassle of configuring createdAt manually (and you can also enable automatic updates for updatedAt).

    token: { type: String, required: true },
  },
  {
    timestamps: true
  } 
);

Answer №3

I encountered a similar problem. Despite having a correct schema file, the issue persisted due to my unintentional import of the model in a react component file

 import room from "../models/room";

Answer №4

I encountered a similar issue and was able to fix it using the solution below:

export default mongoose.models?.User || mongoose.model('User', UserSchema)

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

Issue with JavaScript: Flag set to false does not halt the simple animation

My goal is to initiate animations when the mouse is pressed down and then immediately halt them once the mouse is released. Upon pressing the mouse, I set a flag to true which triggers the animation of the corresponding button that was clicked. However, t ...

Troubleshooting issue with jQuery animate not correctly scrolling

I am experiencing an issue with my jQuery code that is supposed to scroll a smaller container element within a larger container element when a button is clicked. Despite testing with an alert and verifying that the code is working, the scrolling functional ...

What is the best way to extract text from a list item in an unordered list (

I am trying to search a ul list that populates a ddSlick dropdown box. ddSlick adds pictures to list items, making it a visually appealing choice. To see more about ddSlick, you can visit their website here: Here is the code I am using to loop through the ...

The issue arises with loading data from the server due to lack of definition of Mongo

I am experiencing a console bug and need assistance. It seems that there is an issue with loading data from the server as I am getting an error stating "Mongo is not defined." C:\Users\Robert\Desktop\FINISH\node_modules\mongod ...

DOCKER: Encounter with MongooseError [MongooseServerSelectionError] - Unable to resolve address for mongo

I am currently attempting to establish a connection between MongoDB and my application within a Docker container. Utilizing the mongoose package, here is the code snippet that I have implemented: mongoose.connect("mongodb://mongo:27016/IssueTracker", { us ...

How can we enhance Backbone.sync() at the Model level to include additional parameters?

Currently, I am facing a challenge with overriding Backbone's sync() method for a Model. I have the function signature set up and it is triggered correctly, but I am unsure about what needs to be included in the function body in order for it to automa ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

Sending data with the request body using Express and Passport

I've created a login application using Express and Passport, but I'm having trouble directing the user to their specific user profile page. The goal is for users to fill out an HTML form and then be redirected to their own profile page (which dif ...

What is the best way to trigger the download of an image file created by PHP to a user's computer?

My PHP code (upload.php) allows users to upload an image from index.html, resize it, add a watermark, and display it on the same page. Users can download the watermarked image by using the 'Save image as...' option. The resized image is saved in ...

What is the best way to manage a situation where a web element is removed from the DOM while using Selenium Web

On the Sign In page of , I am struggling to extract the value of a label identified by the xpath=".//*[@id='msgIdmmrka']." This particular web element disappears from the DOM a few seconds after entering no email address, a valid password, and cl ...

Running pug directly from the local node_modules directory

I'm currently attempting to run pug (/jade) from my node_modules directory, however I am unable to locate the executable within the node_modules/.bin folder. I am running MacOS 10.12.5 and installed pug using the "npm install --save pug" command. Is ...

I am experiencing issues with icons not loading correctly after changing my module, with error messages indicating issues with cross-origin

Exploring various online tutorials to master the art of Angular programming has been quite an adventure for me. One tutorial introduced a module defined in this manner: .module('MyApp') However, any attempt to modify the name resulted in an er ...

Vanilla JS causing event to fire repeatedly

My code is written in Vanilla JS and I've encountered an issue with dynamically generated content. Each click on the dynamic content returns a different value than expected: First click: 1 Second click: 3 Third click: 6 Fourth click: 10 But it sh ...

How to stop the page from scrolling up when a component is recreated in NextJS/React

I have developed an application where users can post comments and edit them using markdown. However, I am facing an issue when I press the edit button to change the editing state – the markdown editor is created correctly but the page automatically scrol ...

Passing the index in React Native

I am currently developing a music app utilizing the react-native-track-player library. I have created three components named Clusters, Songlist, and Play. Understanding How the Screen Works The flow of components is as follows: Clusters component -> Song ...

Enhance the speed of webview on Android devices

I have been working on an application that utilizes a webview to load both HTML and JavaScript files. Unfortunately, I have noticed a significant decrease in performance when displaying the content. Despite trying various solutions such as: webVi ...

What could be causing Next.js middleware to run repeatedly?

Recently, I set up a brand new Next.js project using npx create-next-app@latest --typescript. Upon completing the installation (version 13.3.4), without making any modifications to existing files, I introduced a new file named middleware.ts within the src ...

Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me. public IActionResult TakeComplexArray(IList<ComplexArrayInfo ...

Having trouble establishing a connection to MongoDB from Node.js

Currently, I am in the process of working on a small blockchain prototype to enhance my understanding before delving into a larger project. After downloading MongoDB, I successfully executed the "mongod" command through CMD. However, upon attempting to in ...

Navigating through two nested arrays in JavaScript to access an object

Having difficulty extracting the nested car values using JavaScript (lodash). Take a look at the JSON data below: { "cars":[ { "nestedCars":[ { "car":"Truck", "color" ...