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

Tips for infuriating TSC with Lookup categories

I'm looking for the Typescript compiler (TSC) to throw errors when I make mistakes in signatures. export class EventEmitter<EventTypes extends { [key: string]: any }> { subscribe<Event extends keyof EventTypes>(type: keyof EventTypes, ...

What is the best way to organize angularjs controllers and directives within one another?

When I structure my controllers like this: <body ng-app="app" ng-controller="ctrl"> <div ng-controller="app-get"> <app-get></app-get> </div> <div ng-controller="app-post"> <app-post">& ...

What is preventing me from mapping an array to Material UI Chip components?

I'm currently working with Next.js and I'm trying to map an array of elements to Material-UI chip components. However, when I compile the code, I encounter the following error: Error: Element type is invalid: expected a string (for built-in comp ...

Angular 6 implement a waiting function using the subscribe method

I need to make multiple calls to a service using forEach, where each call depends on the completion of the previous one. The code is as follows: itemDefaultConfiguration.command = (onclick) => { this.createConfiguration(configuration.components); ...

Implementing Ajax calls to dynamically update Datatable results

Currently integrating Datatables.js with an ajax call for data retrieval. The json response I'm receiving is as follows: "success":true,"message":"","items":[{"id":"1","ip_address":"127.0.0.1","email... My data is stored within the data.items array ...

Using ajax for transferring form data to a different php page

Hello everyone, I'm in need of assistance. I have a form on one PHP page and I want to use AJAX to pass the data to another PHP page that will update my database and then return the results. <form name="profile" class="profile"> < ...

Incorporate a fresh key-value pair into the Redux Toolkit's state

I am currently working on an application that enables users to create and modify recipes. To manage the state, I have chosen to utilize React Toolkit and Redux. Here is an example of the state structure: const ingredients = [ { ingredientName: &apos ...

Experiencing 429 Too Many Requests error on Angular 7 while attempting to perform multiple file uploads

Whenever I attempt to upload a large number of files simultaneously, I encounter an issue. The API interface only allows for the submission of one file at a time, requiring me to call the service for each individual file. Currently, my code looks like thi ...

Filtering database records using a static dropdown list in MVC 5: A step-by-step guide

Is there a way to filter database records based on the columns QtyRecieved, QtyRecievedand Void using a static HTML dropdown list? The QtyRecieved and QtyRecievedand column are both decimal values, while Void is a boolean. This is what I have attempted: ...

Transferring data from a callback function within a component to a different component

I am currently utilizing the giphy-api module in Node.js and I need to transfer this data to React. Within my setup, I have two key components: The first component, Api.js, effectively connects with Node.js and returns a callback containing all of the AP ...

Cannot locate module using absolute paths in React Native with Typescript

I recently initiated a new project and am currently in the process of setting up an absolute path by referencing this informative article: https://medium.com/geekculture/making-life-easier-with-... Despite closely following the steps outlined, I'm en ...

Retrieving device information through JavaScript, jQuery, or PHP

Looking to build a website that can identify the device name and model of visitors accessing the page from their devices. ...

Switch between selecting every group of 3 items and every group of 4 items

Having an array with more than 14 items, I need to group them into 2 different groups in this specific way: The first 3 (#1,2,3) will be in array A, the next 4 (#4,5,6,7) will be in array B, the following 3 (#8,9,10) will be in array A, the subsequent 4 (# ...

obtaining the controller output in JavaScript

Scenario: Retrieving id in javascript following an ajax post I'm trying to figure out how to access the id sent from my controller's ActionResult in javascript. I've experimented with both Content Result and JSON Result on the controller, b ...

Creating a dynamic search feature in mongoose requires utilizing the built-in functions and

I am looking to implement a dynamic search using Mongoose based on the URL provided in the request. For example, here is a sample URL: Users should be able to select multiple colors and genders, resulting in a URL like this: In my MongoDB database, I ha ...

Loading a specific CSS file along with an HTML document

Creating a responsive website, I'm looking to incorporate a feature that allows for switching between a mobile version and a standard desktop version similar to what Wikipedia does. To achieve this, I would need to reload the current HTML file but en ...

Type 'Partial' cannot be assigned a value when combining interfaces with generic types

Consider the following scenario: class Table<ValuesType extends DefaultTableValues = DefaultTableValues>{ public values: ValuesType; constructor(initialValues:ValuesType) { this.values=initialValues; } public set(newValues:Pa ...

How can nextJS leverage async getInitialProps() method in combination with AWS S3?

I'm currently facing a challenge with executing an s3.getObject() function within an async getInitialProps() method in a nextJS project. I'm struggling to properly format the results so that they can be returned as an object, which is essential f ...

What is the best way to retrieve an object within a class?

Exploring a Class Structure: export class LayerEditor { public layerManager: LayerManager; public commandManager: CommandManager; public tools: EditorTools; constructor() { this.commandManager = new CommandManager(); this.lay ...

What could be causing my Link to malfunction in my about.js file?

I've encountered an issue where clicking the link in my app doesn't produce any result, and I'm unsure of the cause. Below is the content of my app.js file: import './App.css'; import {BrowserRouter as Router, Routes, Route} from ...