Using Typescript to Define Mongoose Schemas

Currently exploring the creation of a user schema in TypeScript. I've observed that many people use an interface which functions well until I introduce a message involving username.unique or required property.

No error code present:

import {model, models,Schema,Document } from "mongoose";

interface UserType extends Document{
    username : string,
    email : string,
    password : string,
}

const userSchema = new Schema<UserType>({
    username : {
        type : String,
        required : true,
        trim : true,
        minlength : 3
    },
    email : {
        type :  String, 
        required : true,
        trim : true,
        lowercase : true,    
    },


})

However, upon adding messages, a squiggle error occurs.

import {model, models,Schema,Document } from "mongoose";

interface UserType extends Document{
    username : string,
    email : string,
    password : string,
}

const userSchema = new Schema<UserType>({
    username : {
        type : String,
        required : [true, "Username is required"],
        unique : [true, "Username is already taken"],
        trim : true,
        minlength : 3
    },
    email : {
        type :  String, 
        required :[ true, "Email is required"],
        unique : [  true, "Email is already in use"],
        trim : true,
        lowercase : true,    
    },


})

Error message received:

Type '{ type: StringConstructor; required: [true, string]; unique: (string | true)[]; trim: true; minlength: number; }' is not assignable to type 'SchemaDefinitionProperty<string> | undefined'.
  Types of property 'unique' are incompatible.
    Type '(string | true)[]' is not assignable to type 'number | boolean | undefined'.ts(2322)

In search for an effective solution to this issue or whether utilizing a hybrid JS + TS approach is recommended. Thoughts?

*PS: Working on a next.js project*

Answer №1

According to the feedback provided, it appears that using [true, "message"] as a value for the unique property is not valid since it is not recognized as a validator based on the documentation referenced below.

https://mongoosejs.com/docs/validation.html#the-unique-option-is-not-a-validator https://mongoosejs.com/docs/faq.html#unique-doesnt-work

The required attribute functions properly with the [true, "message"] syntax.

If there is a strong desire to override the typing and bypass this limitation at all costs, one possible workaround is to cast the SchemaType as any:

This method is not recommended

import {model, models,Schema,Document } from "mongoose";

interface UserType extends Document{
    username : string,
    email : string,
    password : string,
}

const userSchema = new Schema<UserType>({
    username : {
        type : String,
        required : [true, "Username is required"],
        unique : [true, "Username is already taken"],
        trim : true,
        minlength : 3
    } as any,
    email : {
        type :  String, 
        required :[ true, "Email is required"],
        unique : [  true, "Email is already in use"],
        trim : true,
        lowercase : true,    
    } as any,
})

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

Unable to find the locally stored directory in the device's file system using Nativescript file-system

While working on creating an audio file, everything seems to be running smoothly as the recording indicator shows no errors. However, once the app generates the directory, I am unable to locate it in the local storage. The code I am using is: var audioFo ...

What could be the reason for the variable's type being undefined in typescript?

After declaring the data type of a variable in TypeScript and checking its type, it may show as undefined if not initialized. For example: var a:number; console.log(a); However, if you initialize the variable with some data, then the type will be display ...

Issue with detecting window resize event in Angular 7 service

I have a unique service that utilizes a ReplaySubject variable for components, but strangely the WindowResize event isn't triggering. import { Injectable, HostListener } from '@angular/core'; import { ReplaySubject } from 'rxjs'; ...

Encountering the "TypeError: Cannot call a class as a function" error while using EditorJS in NextJs

I am facing an issue with integrating EditorJs into my NextJs app. This is what I have tried: Editor.js import dynamic from "next/dynamic"; let CustomEditor = dynamic(() => import("./CustomEditor"), { ssr: false ...

Preventing a user from accessing the login page if they are already logged in using Reactjs

I need assistance with implementing a "Login Logout" module in Reactjs using the nextjs framework. My goal is to redirect users to the "dashboard" page if they are logged in (email set in cookie). However, I am encountering an error with the following co ...

Cached images do not trigger the OnLoad event

Is there a way to monitor the load event of my images? Here's my current approach. export const Picture: FC<PictureProps> = ({ src, imgCls, picCls, lazy, alt: initialAlt, onLoad, onClick, style }) => { const alt = useMemo(() => initial ...

The array is not empty but the length is being displayed as zero

I am facing an issue in my project where I can successfully print the array in console, but I am unable to retrieve the length and access the first element. Here is the code snippet: checkout.component.ts: ngOnInit() { this.booksInCheckout = this.ch ...

Guide to building a nested React component

My custom dropdown component requires 2 props: trigger (to activate the dropdown) list (content to display in the dropdown) Below is the implementation of my component: import { useLayer } from "react-laag"; import { ReactElement, useState } fr ...

React is unable to assign a class field beyond the scope of axios

class App extends React.Component { app: Application; ... componentDidMound() { axios.get(…).then(res => { this.app.currentUser = res.data.data; // setting value inside lambda function. console.log(this.app.currentUser); // ...

Obtain the specific generic type that is employed to broaden the scope of a

I am working on a class that involves generics: abstract class Base<P extends SomeType = SomeType> { // ... } In addition, there is a subclass that inherits from it: class A extends Base<SomeTypeA> { // ... } I'm trying to figure out ...

How can you line up various form elements, like pickers, in a row using Material UI?

As someone new to material ui, I haven't come across a solution for my specific issue yet. While there are similar questions, none seem to address the problem of aligning different form field types. My observation is that the material ui date picker ...

User interface designed for objects containing multiple keys of the same data type along with a distinct key

I have a question that relates to this topic: TypeScript: How to create an interface for an object with many keys of the same type and values of the same type?. My goal is to define an interface for an object that can have multiple optional keys, all of t ...

Simultaneous Activation of Hover Effects on Multiple Elements

I have an array of objects that I'm iterating over. Here is the array: const socialLinks = [ { id: 1, child: ( <> <FaLinkedin className='text-2xl' /> Linkedin </> ), hre ...

Having trouble setting my cookie in Next.js. Getting error message: Cannot access properties of null while trying to read 'useContext'

I am encountering an issue with the next-auth implementation. I am trying to set a cookie, but I am having trouble figuring out how to do it. auth.js import { useCookies } from "react-cookie"; import { setCookies } from 'cookies-next'; ...

Updating multiple documents in mongoose using Node JS is a breeze

When attempting to update multiple documents using a query generated from an object array, I encountered an issue where only one document was actually modified. var split = num.toString().split(','); var list = new Array; for ( var i in split ) ...

Is there a way to determine the compatible browser version for Next.js 12.3?

I am looking to develop a Next.js 12.3 project that is compatible with specific browser versions as indicated in the image below. While I have referred to https://nextjs.org/docs/architecture/supported-browsers, it seems to be focused on Next.js 13. Here ...

What is the process to enable a deployed React app (hosted in S3) to retrieve JSON data that is uploaded to an S3 bucket?

I'm in the process of creating a static React App that showcases API documentation. Utilizing Swagger for the backend (which is hosted separately on a lambda) to generate the JSON data model. I have another lambda set up to provide me with endpoint de ...

Is it possible to utilize an XML format for translation files instead of JSON in React Native?

I'm in the process of creating a react native application using the react i18next library. For translations, I've utilized XML format in android for native development. In react native, is it possible to use XML format for translation files inste ...

The error message "FormData parsing error: final boundary is missing" appears due

Recently, I made the switch from node to bun in a Next.js project. However, when trying to parse form data, I encountered this error: 14 | const POST = async (request)=>{ 15 | try { 16 | console.log("request: ", await request.heade ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...