NestJS Ensures Type Safety for Mongoose Models, but Model Functions Expecting Incorrect Types (Any)

Shema Interfaces

export interface MyCat {
  name: string;
  color: string;
}

export type Cat = MyCat & Document;

export const CatSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  color: {
    type: String,
    required: true,
  }
});

The data transfer object that the function is supposed to receive (without a color property)

export class CreateCatDto {
  @IsString()
  readonly name: string = 'Franco';
}

When the function is called, it does not show any error on new Cat(cat), but throws an error at runtime in Mongoose stating missing required attributes.

  constructor(@InjectModel('Cat') private readonly catModel: Model<Cat>) {}

  async create(cat: CreateCatDto) {
    // I expect TypeScript to give me an error here :(
    const createdCat = new this.catModel(cat);
    return await createdCat.save();
  }

My concern is, how can I ensure that the model functions understand what they need to receive accurately? It seems like they often just accept the any type.

Answer №1

If you're looking for a tool to create typesafe models, check out Typegoose at .

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 abbreviation for indicating a return type as nullable?

Is there a way to use shorthand for nullable return types in TypeScript similar to using "name?: type" for parameters? function veryUsefulFunction(val?: string /* this is OK */) // but not this or other things I've tried. // is there a way a ...

Generating a collection of objects using arrays of deeply nested objects

I am currently working on generating an array of objects from another array of objects that have nested arrays. The goal is to substitute the nested arrays with the key name followed by a dot. For instance: const data = [ id: 5, name: "Something" ...

Trouble with PUT request for updating user password using Express.js with mongoose

I've encountered a puzzling issue while working on my Express.js application. Specifically, I have created an endpoint for updating a user's password. Surprisingly, the endpoint functions flawlessly with a POST request, but fails to work when swi ...

typescript: define the type of an object that behaves like a map

My current approach involves utilizing an object to store a map, where keys are strings and values are of a fixed type T. Upon looking up a key in the object, the type inference automatically assigns it the type T. However, there is a possibility that it ...

Ensuring that environment variables are properly set is essential for effective error handling

I am currently integrating my NodeJS and Typescript App to create new config files that utilize .env variables. If a specific variable is not set, I want to trigger an error. After setting up my config file, I encountered some errors; however, I am unsure ...

After integrating React Query into my project, all my content vanishes mysteriously

Currently, I am utilizing TypeScript and React in my project with the goal of fetching data from an API. To achieve this, I decided to incorporate React Query into the mix. import "./App.css"; import Nav from "./components/Navbar"; impo ...

Having trouble with Angular 5 tsconfig baseURL not functioning properly?

This may appear straightforward, but I am facing difficulties with it My Angular 5 application consists of three files located as follows: app_directory/tsconfig.json app_directory/src/app/services/my-service.service.ts app_directory/src/app/main/sub1/su ...

Error: Unhandled promise rejection - The function get is not part of this.categoryMap

I am facing an issue with calling functions of the Map (get, set, keys, etc) within my function. The map I am working with is returned from a firebase query. Here's a snippet of my code: categoryMap = new Map<Number, String>(); //called onInit ...

Angular: How can the dropdown arrow in 'ng-select' be eliminated?

Is there a way to hide the dropdown arrow in an 'ng-select' element in Angular? <div class="col-md-6"> <ng-select id="selectServiceType" [items]="clientServiceTypes$ | async" pl ...

Encountering an error when updating two mongoose collections: "Unable to set header after it has been sent."

Currently, I am working on creating a collection called requests with two fields: photographers and users. My goal is to update the user with the request_id so that I can utilize the .populate() method in the user dashboard to showcase the users' requ ...

Using TypeScript's Non-Null Assertion Operators in combination with square brackets []

One way to assert that an object has a certain property is by using the `!.` syntax as shown below: type Person = { name: string; age: number; gender?: string; } const myPerson: Person = { name: 'John Cena', age: 123, gender: 's ...

Enabling Cross-Site Request Forgery (CSRF) through Angular's HttpClientModule is causing an error message to appear: TS2552 -

As a novice in front-end development, I am looking to incorporate CSRF tokens into certain requests within a frontend application. The app is built using Angular version 12.2.17, and I am following the guidelines outlined in the Angular documentation: http ...

Typescript is failing to perform type checking

I'm encountering an issue while trying to utilize TypeScript type checking with the following code snippet: abstract class Mammal { abstract breed(other: Mammal); } class Dog extends Mammal { breed(other: Dog) {} } class Cat extends Mammal { ...

A guide on updating a MySQL table using a JSON object in Node.js

I have a JSON Object and need to UPDATE a mySQL table without listing all of the keys individually For an INSERT operation, I use the following code: var arrayValue = Object.keys(obj).map(function(key) { return String("'"+obj[key]+"'"); ...

Typescript and RxJS: Resolving Incompatibility Issues

In my development setup, I work with two repositories known as web-common and A-frontend. Typically, I use npm link web-common from within A-frontend. Both repositories share various dependencies such as React, Typescript, Google Maps, MobX, etc. Up until ...

Can Typescript automatically determine the return type based on the function argument value?

How can Typescript be utilized to deduce the return type from the valueType parameter instead of using overloads? type ValueType = 'integer' | 'string' | 'number' | 'date' | 'dateTime' | 'boolean&apos ...

Guide on showing a component exclusively for iPads with React and TypeScript

I need help displaying an icon only in the component for iPad devices, and not on other devices. As a beginner in coding for iPads and mobile devices, I am unsure how to achieve this specific requirement for the iPad device. Below is the code snippet tha ...

Building a PathString Tree

I encountered a similar issue like the one discussed in this post (Get a tree like structure out of path string). I attempted to implement the suggested solution but I am facing difficulties getting it to work within an Angular context. The concept involv ...

I am looking to transfer 'beforeEach' and 'afterEach' from the spec file to the global configuration file in WDIO [mocha, hook, wdio]

My E2E testing setup involves using the WebdriverIO library along with the mocha framework. During test execution, I want Mocha to automatically skip all subsequent checks in a test after encountering the first error, and proceed to the next test file. T ...

Getting an error message with npm and Typescript that says: "Import statement cannot be used outside

After developing and publishing a package to npm, the code snippet below represents how it starts: import * as aws from "@pulumi/aws"; import * as pulumi from "@pulumi/pulumi"; export interface ... export class controlplaneDependencies ...