Typescript is throwing a Mongoose error stating that the Schema has not been registered for the model

I've dedicated a lot of time to researching online, but I can't seem to figure out what's missing in this case. Any help would be greatly appreciated!

Permission.ts (This is the Permission model file. It has references with the Module model via "ModelID")

import mongoose from 'mongoose';

// An interface that outlines the necessary properties
// to create a new User
interface PermissionAttrs {
  Code: string;
  Name: string;
  Description: string;
  ModuleID: string;
  Active: boolean;
  CreatedByUserID: string;
  UpdatedByUserID: string;
  createdAt: Date;
  updatedAt: Date;
}

// Interface describing the properties a User Model has
interface PermissionModel extends mongoose.Model<PermissionDoc> {
  build(attrs: PermissionAttrs): PermissionDoc;
}

// Interface describing the properties a User Document has
interface PermissionDoc extends mongoose.Document {
  Code: string;
  Name: string;
  Description: string;
  ModuleID: string;
  Active: boolean;
  CreatedByUserID: string;
  UpdatedByUserID: string;
  createdAt: Date;
  updatedAt: Date;
}

const PermissionSchema = new mongoose.Schema(
  {
    // Schema definitions here...
  });

PermissionSchema.statics.build = (attrs: PermissionAttrs) => {
  return new Permission(attrs);
};

const Permission = mongoose.model<PermissionDoc, PermissionModel>(
  'Permission',
  PermissionSchema
);

export { Permission };

Module.ts (This is the Module model file)

import mongoose from 'mongoose';

// Interfaces and Schema definitions for Module...

ModuleSchema.statics.build = (attrs: ModuleAttrs) => {
  return new Module(attrs);
};

const Module = mongoose.model<ModuleDoc, ModuleModel>('Module', ModuleSchema);

export { Module };

This code snippet is used in the route:

import { Permission } from '../models/permission';
...
const Items = await Permission.find()
        .populate('ModuleID')
        .or(filter || {})
        .sort(sort || {})
        .skip(start || 0)
        .limit(length || 0);

      console.log(Items);

Error Message:

“Mongoose error MissingSchemaError: Schema hasn't been registered for model Module”

I've spent all day trying to pinpoint the issue without success. Can someone please point me in the right direction? What am I missing?

Answer №1

To ensure the correct functionality, it is important to include the Module file at the start of your route.

import { Module } from '../models/Module';
import { Permission } from '../models/permission';
...
const Items = await Permission.find()
        .populate('ModuleID')
        .or(filter || {})
        .sort(sort || {})
        .skip(start || 0)
        .limit(length || 0);

      console.log(Items);

It is crucial to execute the following line in order to register the schema for the Module model:

const Module = mongoose.model<ModuleDoc, ModuleModel>('Module', ModuleSchema);

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

javascript detect when two div elements are overlapping

On my webpage, I have implemented the effect.shrink() function. However, when clicking quickly on the page, the div tags start overlapping with other elements. What is the best way to solve this issue? I am using both scriptaculous.js and prototype.js fo ...

Having difficulty retrieving model values from the angular ui modal dialog

Being only on my second day in the world of Angular, I am trying to navigate around Angular UI and build my first modal dialog. The modal dialog displays properly, but I'm encountering an issue with using models within it. You can view my demo on Plun ...

Transformation of visuals with alteration of status

I am attempting to change the image of a door from closed to open when the status changes in my home automation dashboard. I need help with this task. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&qu ...

Does AngularJS have a similar function to $(document).ajaxSuccess()?

When working with AngularJS, I am looking to implement a universal ajax loader that does not require integration into each controller to function. In jQuery, this can be achieved through the following code: (function globalAjaxLoader($){ "use strict"; ...

Is it possible to simultaneously run multiple functions with event listeners on a canvas?

I'm attempting to create a canvas function that displays the real-time mouse cursor location within the canvas and, upon clicking, should draw a circle. I came across this code snippet that reveals the x and y coordinates of the mouse: document.addEve ...

Issues with Angular and Bootstrap: ng-hide functionality not functioning correctly

I am struggling to grasp the concept of the ng-show angular directive as it is not functioning correctly for me. Despite following some examples I found online, I cannot seem to change the boolean value in the controller like they suggest. Instead of using ...

Adjusting the selected state of an HTML/CSS checkbox with JavaScript

After downloading a theme with a tailored switch component that replaces the standard checkbox functionality, I noticed that the 'checked' status of the underlying checkbox does not change upon click or touch events. Here is the HTML structure: ...

Display a division upon choosing an option

I am working on a project that involves a selection menu in the form of a drop-down list. <select> <option id="one" value="something">Car</option> <option id="two" value="anything">Plane</option> </select> Also, I ...

The functionality of the ajax hash navigation feature seems to be malfunctioning

I've been trying to use hashes for my navigation, but everytime the page loads, my script resets the initial hash to #home. It doesn't matter what hash I add in the URL: Here is the script that runs to check if the hash exists and what content t ...

Why is the localhost not loading despite having the node server and mongodb running?

I recently began learning about MEAN development. I managed to set up my express server and establish a connection with mongodb. When I run node server in the terminal, the server starts running and the connection to mongo is successful. However, when I tr ...

Use Vue 2 with TypeScript to prevent directly changing Props in a class-based component using vue-property-decorator

Is there a way to declare a Prop using vue-property-decorator in a class-based component without the need to initialize it? Currently, I'm facing a dilemma: If I don't provide an initializer, TypeScript throws an error during compilation: ...

Is an internet connection necessary for a node.js server to operate?

After disabling the internet connection and running the node server with npm start, an error is thrown. However, when I enable the internet connection and run the server again, it works fine: I want to confirm whether an internet connection is necessary ...

Error: The lockfile and package.json file are not synchronized when running npm

Having a problem with NPM where the package-lock and package.json files are out of sync. Tried deleting node_modules, running npm install, but issue persists. Any suggestions? Error: npm ci can only install packages when package.json and package-lock.json ...

Mapping a JavaScript object to an MVC model: A comprehensive guide

I have a JavaScript object as shown below: $scope.docPropIdentityModel = { Owner: {OwnerID:"", OwnerName: ""}, }; I need to send this object to my MVC controller using an AJAX call. Let's say the controller looks like this: controll ...

How can models be aggregated in SQL by connecting them through other models?

I am working with a backend express API that utilizes sequelize. In my sequelize models, a Citizen is linked to a Street, which in turn is associated with a Town, and the Town is connected to a State. I can easily count the citizens on a specific Street by ...

Using jQuery to create a seamless transition in font size as you scroll

Currently, I have a jQuery animation function in place to adjust the font size of the .header-wrap text when the document is scrolled beyond 50px. While this method does work, I am not completely satisfied with it as the transition is not very smooth. Idea ...

What steps should I take to address the issue of the document not being defined?

I encountered an error that I initially thought was related to node.js, but now I'm not entirely sure. How can I go about resolving this issue? [Running] node "c:\Users\Lenovo\Desktop\projectjs\index.js" c:\User ...

How do the JavaScript thread and the Silverlight UI thread interact with each other?

While JavaScript operates on a single thread, Silverlight does not follow the same restrictions. However, when it comes to the interaction between JavaScript and Silverlight, it is crucial that communication occurs on the Silverlight UI thread. The relati ...

Tips for effectively injecting retrieved API response data into a Table

Creating a google-map with customized markers that are logos of companies is the goal. Obtaining a json file from the APIs containing the vessels of interest has been successful. The challenge faced is injecting these vessels into a table on the user inte ...

When attempting to pass props to children, Typescript triggers an error message

I am facing an issue with a component that renders a child based on the specific "league" a user is viewing, such as MLB. Typescript is throwing an error because I am not passing the correct props to the child component. However, the parent component has t ...