The Typing of Mongoose 5.11.11 Schema Definitions

Recently, there was an update in Mongoose that allows it to accept a model generic. While it works perfectly fine with a string type, it seems to have trouble with a boolean type, giving the error message

Type 'boolean' is not assignable to type 'SchemaDefinitionProperty<undefined>'
.

interface User {
  firstName: string;
  lastName: string;
  email: string;
  password: string;
  isVerified?: boolean;
}

const UserSchemaDefinition: SchemaDefinition<User> = {
  firstName: {
    type: String,
    trim: true,
    required: true,
  },
  lastName: {
    type: String,
    trim: true,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
    private: true,
  },
  isVerified: {
    type: Boolean,
    default: false,
  },
};

const UserSchema = new mongoose.Schema(UserSchemaDefinition); // Issue arises here.

An example related to this issue can be found at this link.

Answer №1

(information) definition: mongoose.SchemaDefinition<T>
Issue with type 'SchemaDefinition<T>' when trying to assign it to a parameter of type 'SchemaDefinition<SchemaDefinitionType<T>> | undefined'.
  The object type '{ [path: string]: SchemaDefinitionProperty<undefined>; } | { [path in keyof T]?: SchemaDefinitionProperty<T[path]> | undefined; }' is not compatible with the type 'SchemaDefinition<SchemaDefinitionType<T>> | undefined'.
    The object type '{ [path: string]: SchemaDefinitionProperty<undefined>; }' cannot be assigned to the type 'SchemaDefinition<SchemaDefinitionType<T>>'.
      The sub-object type '{ _id?: SchemaDefinitionProperty<any> | undefined; __v?: SchemaDefinitionProperty<any> | undefined; $getAllSubdocs?: SchemaDefinitionProperty<...> | undefined; ... 52 more ...; validateSync?: SchemaDefinitionProperty<...> | undefined; }' does not match the type 'SchemaDefinition<SchemaDefinitionType<T>>'.

import mongoose, {
  model, Schema, Model, Document, SchemaDefinition,
} from 'mongoose';

const express = require('express');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');

interface IUser extends Document {
  email: string;
  firstName: string;
  lastName: string;
}

interface IDocUser extends mongoose.Document, IUser { }

interface UserSchemaProps {
  email: typeof String;
  firstName: typeof String;
  lastName: typeof String;
}

function createSchema<T extends mongoose.Document>(definition: SchemaDefinition<T>) {
  return new Schema<T>(definition);
}

const UserSchemaDefinition: mongoose.SchemaDefinition = {
  email: { type: String, required: true },
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
};

const UserSchema: Schema<IDocUser> = createSchema<UserSchemaProps>(UserSchemaDefinition);

Is there a possible solution to this problem?

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

Is there a way to enhance the functional purity by creating a single function that subscribes and returns a

I'm currently developing a project that involves receiving humidity data from a raspberry pi sensor connected to a backend. Within my Angular Component, I am aiming to display this data in a functional and pure manner. However, I have some doubts rega ...

Isolating a service from a component based on conditions in Angular 5

Within my root module, I have a service that is shared among all components. One of these components is named ComponentX module providers: [ BiesbroeckHttpService ], component constructor(private biesbroeckHttpService: BiesbroeckHttpService){} Som ...

io-ts: Defining mandatory and optional keys within an object using a literal union

I am currently in the process of defining a new codec using io-ts. Once completed, I want the structure to resemble the following: type General = unknown; type SupportedEnv = 'required' | 'optional' type Supported = { required: Gene ...

Filtering function that works without specific knowledge of keys

I'm working on a JavaScript method to filter a list dynamically without knowing the specific key (s). I've made some progress, but I'm stuck and not sure how to proceed. The foreach loop I have isn't correct, but I used it for clarity. ...

Is there a way to incorporate three new fields into a Mongoose Model using the pre function?

I am trying to calculate my overall grade by adding the preliminary, midterm, and final grades together and then dividing by 3. However, the code I have written is returning a null value. I have searched for solutions here, but even after implementing the ...

Categorize items based on their defined attributes using Typescript

[origin object array and expect object array ][1] origin object array: 0: amount: 100000000000000000000 feeTier: 0.3 price: 00000 priceDecimal: 0000 status: "unknown" tokenXAddr: "0x*********" tokenXSymbol: "USDC" tokenYAddr: ...

Angular 15 experiences trouble with child components sending strings to parent components

I am facing a challenge with my child component (filters.component.ts) as I attempt to emit a string to the parent component. Previously, I successfully achieved this with another component, but Angular seems to be hesitant when implementing an *ngFor loop ...

UI not reflecting updated form validation after changes made

Currently, I have a situation where I am passing a form from the Parent component to the Child component. All the validations are being handled in the Parent component and the Child component is simply rendering it. However, there is a specific field calle ...

Having difficulty altering the color of an element in Viewer

Currently, I am conducting a PoC and experimenting with changing the color of a selected element to red. Despite creating a class as shown below, I am facing issues where the elements do not change color when selected. I have attempted various examples fro ...

What is the best method for storing my MonjaDB credentials in order to securely access my MongoDB database

As I experiment with the MonjaDB (eclipse plugin) for connecting to a sharded MongoDB database remotely, I find that it repeatedly prompts for the username and password for every command I attempt to execute. This limitation significantly reduces the usefu ...

What is the best way to display values from a Localstorage array in a tabular format using a looping structure

I have set up a local storage key 'fsubs' to store form submissions as an array. Here is how I am doing it: var fsubs = JSON.parse(localStorage.getItem('fsubs') || "[]"); var fcodes = {"barcodeno" : this.form.value.barcode, "reelno" : ...

Retrieve and showcase information from Firebase using Angular

I need to showcase some data stored in firebase on my HTML page with a specific database structure. I want to present the years as a clickable array and upon selecting a year, retrieve the corresponding records in my code. Although I managed to display a ...

Issues encountered with connecting to MongoDB

Having trouble connecting MongoDB to node.js, even though MongoDB is running I keep getting this error. [terminal]JavaScript code Attempted to restart MongoDB but the issue persists. ...

Transforming TypeScript snapshot data in Firebase Cloud Functions into a string format for notification purposes

I've encountered the following code for cloud functions, which is intended to send a notification to the user upon the creation of a new follower. However, I'm facing an issue regarding converting the snap into a string in order to address the er ...

Leveraging TypeScript alongside body-parser to access properties within req.body

I'm currently developing a web application using TypeScript and integrating the body-parser middleware to handle JSON request bodies. I've encountered type errors while attempting to access properties on the Request.body object. For instance, wh ...

Tips for retrieving next-auth authOptions from an asynchronous function

I need to retrieve values from AWS Secrets Manager and integrate them into the authOptions configuration for next-auth. The code implementation I have is as follows: export const buildAuthOptions = async () => { const secrets: AuthSecrets = await getS ...

Mastering the art of utilizing connect-mongo, discovering the ins and outs of incorporating connect-mongo for seamless session

In my Node.js application, I am attempting to save session data to a MongoDB database. However, I am struggling with the proper usage of connect-mongo and would appreciate some guidance on how to correctly establish the connection to my MongoDB database. ...

Transforming two child arrays within an object into a single array using Ramda

I am looking to transform an object into an array. The object I have is structured like this: const data = { t1: [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ], t2: [ {" ...

Transforming TypeScript declaration files into Kotlin syntax

Has there been any progress on converting d.ts files to Kotlin? I came across a post mentioning that Kotlin developers were working on a converter, but I am unsure about the current status. I also found this project, which seems to be using an outdated c ...

Angular Error TS2554: Received x arguments instead of the expected 0 on piped operators

I encountered an issue with Error TS2554: Expected 0 arguments, but got 4 when dealing with the observable getHappyDays(). The getHappyDays() Observable returns either Observable<HttpResponse<IHappyDays>> or Observable<HttpErrorResponse> ...