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

What is the best way to implement auto-saving functionality for multiple form fields in a React application?

Whenever I make changes to the first and second columns of an item in a text field, the onBlur event triggers an auto-save. This results in the entire row being reloaded due to the update caused by the first column's save. Is there a way to prevent t ...

JavaScript - Toggling checkboxes to either be checked or unchecked with a "check all" option

To create a toggle checkboxes functionality, I am attempting the following: HTML Code: <!-- "Check all" box --> <input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox( this.getAttribute( 'id' ));" /> <!-- the other ...

Express Module Employs Promises for Returns

I have a JavaScript file for elasticsearch (could be any other database as well) that performs a simple query and uses a promise to return the data. I am using this module in my Express server (server.js) with the hope of retrieving the data, as I ultimat ...

Exploring the Uses of SystemJS with TypeScript Loader

Can someone help clarify something about this TypeScript plugin for SystemJS? https://github.com/frankwallis/plugin-typescript/ Here is what the plugin does: This SystemJS plugin allows you to import TypeScript files directly and have them compiled in ...

An obstacle prevents the code injection process in the Chrome extension when a button is pressed

My basic chrome extension is not functioning correctly. More specifically, I am encountering an issue where the alert box does not appear when I click on the button in the popup. Here are the contents of my manifest.json file: {"manifest_version": 2, "n ...

Sending a parameter to the load method of the Selectize jQuery extension

I have a question about using the Selectize jQuery plugin for a dropdown box. I am not very familiar with jQuery, so please bear with me if this is a simple issue. I am making an ajax call to fetch data for the dropdown, but I need to pass a variable to th ...

What methods can I utilize to prevent pop-up errors from appearing in my javascript code?

Recently, I've been working on utilizing an innovative IBM tool called Presto that efficiently transforms traditional green screens into browser-based pages. While the process is effective, it involves some quirky behaviors. One particular challenge I ...

Navigate the page by scrolling the absolute positioned div

Is it possible to make the fancybox modal scroll with the page using fancybox 2? I want it to move along with the content rather than being fixed in the center with a max-height restriction. How can I achieve this? $('.fancybox-open').fancybox({ ...

Tips for preventing JavaScript errors when making cross-domain requests using AJAX

Is there a way to prevent or handle JavaScript errors without causing the script to crash? Error message: No data returned $.ajax({ type : 'GET', dataType : 'jsonp', url : '//cvrapi.dk/api?search=dsfsdfsd&country= ...

Locate the class and execute the function on the existing page

Stepping outside of my comfort zone here and I'm pretty sure what I've come up with so far is totally off. Ajax is new to me and Google isn't making things any clearer, so I was hoping someone more knowledgeable could assist! Basically, I w ...

Switch the image displayed on hover over an image using the #map attribute

Recently, I successfully integrated a database connection into this website and made it dynamic. The overall design of the site was already in place, so my main focus was on adding the functionality of the database connection. However, after implementing ...

Encountering AWS Amplify 503 error while utilizing Next.js getStaticProps with revalidate functionality

I recently encountered an issue while utilizing the Next.js getStaticProps function on a page and deploying it on AWS Amplify. Upon including the 'revalidate' option, a 503 error from AWS Cloudfront was triggered, indicating a permission-relate ...

Tips for sending a query using the http GET method in Next.JS 14 API routes

When using the Next.js 14 API route, I am passing a page in the GET method to paginate the data fetched from my database. However, an error is thrown when trying to retrieve the query from the request: Property 'query' does not exist on type &a ...

My goal is to exclusively create illustrations of items within a camera's view

Currently, I am using THREEJS to create a dynamically generated 'minecraft' world utilizing a perlin noise generator. Check out the progress so far: Block World Everything is going smoothly except that I am facing significant performance issues ...

JQuery may be successfully loaded, but it is not functioning as intended

Just started dabbling in JQuery (I'm a newbie) but I'm having trouble getting it to work! Initially, it worked a couple of times but then suddenly stopped working (pretty strange). I made some changes and now it doesn't work at all. JQuery a ...

The Nodejs function exits before the internal function finishes executing

Currently, I am facing an issue where despite MongoDB returning the correct number of users (more than 0) when running console.log within collection.find(), the function userExists always returns false (0). I'm seeking guidance on how to ensure that ...

JQuery - Triggering mouseenter/hover event only on top-level menu items, excluding the nested submenu items (list items that are not within nested lists)

I have a complex navigation menu structure with nested lists, and I'm struggling to trigger an event only on the top-level items when hovered. Despite trying different jQuery selectors and methods, such as using the NOT selector or targeting direct ch ...

Leveraging dynamic anchor tags within a Chrome extension

In my current project, I am dynamically generating anchor tags and using them to redirect to another page based on their unique IDs. While I have successfully implemented this feature using inline scripts in the past, I ran into an issue with Chrome exte ...

MongoDB - absent in alternate databases (complex many-to-many connection)

Currently, I am in the process of learning how to utilize mongodb and have successfully created 3 collections - User, Enrollment, and Courses. User +--------------------------------------+---------+--------+ | _id | user_id ...

Whenever I attempt to start the server using npm run server, I encounter the following error message: "Error: Unable to locate module './config/db'"

This is the server.jsx file I'm working with now: Take a look at my server.jsx file Also, here is the bd.jsx file located in the config folder: Check out the db.jsx file Let me show you the structure of my folders as well: Explore my folder structur ...