How is it possible that this does not trigger a compile error? (Mongoose, Typescript, MongoDB)

I am in the process of setting up a MERN project in Typescript and I have come across something that puzzles me. Despite my expectations, there is no compilation error in TS with the following code:

Here's the model snippet:

import { Document, Schema, model } from "mongoose";
export interface Hello extends Document {
  name: string;
}

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

const helloModel = model<Hello>("Hello", helloSchema);

export default helloModel;

and it is used as follows:

import express from "express";
import helloModel from "./model";

const app = express();

app.get("/", (req, res) => {
  res.send("hi");
});

const x = new helloModel({ age: 1 }); <===== no errors here

app.listen(7000);

I expected to see compilation errors indicating that x does not match the defined interface. Could it be that I am using the model incorrectly? Being new to MongoDB and Typescript, I might be missing something obvious.

Thank you to anyone who can offer an explanation.

EDIT FOLLOW-UP I discovered this information in the @types files:

/**
     * Model constructor
     * Provides the interface to MongoDB collections as well as creates document instances.
     * @param doc values with which to create the document
     * @event error If listening to this event, it is emitted when a document
     *   was saved without passing a callback and an error occurred. If not
     *   listening, the event bubbles to the connection used to create this Model.
     * @event index Emitted after Model#ensureIndexes completes. If an error
     *   occurred it is passed with the event.
     * @event index-single-start Emitted when an individual index starts within
     *   Model#ensureIndexes. The fields and options being used to build the index
     *   are also passed with the event.
     * @event index-single-done Emitted when an individual index finishes within
     *   Model#ensureIndexes. If an error occurred it is passed with the event.
     *   The fields, options, and index name are also passed.
     */
    new (doc?: any): T;

It appears that the inclusion of doc?: any explains why there is no compile error. Does this mean that in general, when combining Mongo schemas with TS interfaces, we can only enforce type checking on Read, Update, and Delete operations rather than Create?

Answer №1

It is correct that using doc?: any, typechecking cannot be done on the create method. When attempting to save it to the database, an error will occur solely due to schema validation.

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 process for switching the tile layer from OpenStreetMap to Stamen?

Exploring the possibilities of using Stamen maps with ngx-leaflet has piqued my interest. For those interested, more information on integrating leaftlet can be found here. However, the process of integrating it with ngx-leaflet remains a bit unclear to m ...

Leveraging Typescript in Firebase Cloud Functions to effectively work with intricate interfaces

When querying a collection on the app side, I am able to automatically cast the result as an interface using Positions constructor that takes in interface IPosition. However, attempting to do the same on the cloud functions side prevents the functions fro ...

Guide to implementing the get method to parse URL parameters upon button click in a NodeJS, Express, and Mongoose application

I'm currently working on displaying data from a database in a table based on a list of cities. These cities are listed in a select option dropdown. I have successfully managed to retrieve the selected city value in the URL using a form with the GET me ...

What could be causing the "GitHubActionsReporter error" to appear in my Jest testing for express.js?

My journey with jest began as I attempted to test my express endpoints, but encountered the following error while running the tests: Error: Cannot find module './GitHubActionsReporter' To help reproduce this error easily by following the docum ...

Erase a subdocument from a MongoDB collection based on its specific value

I am facing a scenario where my collection consists of documents structured like this: { "user": "foo", "topics": { "Topic AB": { "score": 20, "frequency": 3, "last_seen": 40 }, "Topic BD ...

How can I clear the cache for GetStaticPaths in NextJs and remove a dynamic route?

This question may seem basic, but I can't seem to find the answer anywhere online. Currently, I am diving into NextJs (using TypeScript) and I have successfully set up a site with dynamic routes, SSR, and incremental regeneration deployed on Vercel. ...

The testString's dependencies are unresolved by Nest

Encountered Problem: Facing the following issue while running a unit test case Nest is unable to resolve the dependencies of the testString (?). Please ensure that the argument SECRET_MANAGER_SERVICE at index [0] is available in the context of SecretMa ...

Combining Arrays of Items in Typescript

I am dealing with an array in Angular 14 that looks like this: [ { "parentItem": "WBP258R", "childItem": "WBP258R", "columnName": "Color", "oldValue": ...

Troubleshooting the issue of having multiple menu items in Material UI

Every time I attempt to add the Menu component multiple times, I encounter an issue with the popup list displaying incorrectly. To demonstrate this problem, you can view it through the link provided on codesandbox below. I have included data-id attributes ...

It is essential for the object to contain a method called '[Symbol.iterator]()' which will yield an iterator upon invocation

Currently, I am facing the following error: error TS2488: Type 'Usuario' must have a '[Symbol.iterator]()' method that returns an iterator. This is my code: usuarios.reducers.ts export interface UsuarioState { users: Usuario[]; ...

I am experiencing trouble with printing weatherData on my command line interface

Issue with Weather Data Display in Command Line I am having trouble printing out the weatherData in my console even though I followed the instructions from the provided image URL. Can anyone help me identify the problem and suggest a solution? ...

Retrieving a data type from the key values of deeply nested objects

I'm currently working with JSON data that contains nested objects, and my goal is to extract the unique set of second-level keys as a type. For instance: const json = { 'alice': { 'dogs': 1, 'birds': 4 ...

Can a custom type be created in Typescript that permits objects but excludes Errors?

Currently working on resolving an odd scenario with a logger. Essentially, calls like log({ info: 'information' }) function as expected, but log(new Error()) falls short. While no solution is readily available, the goal is to override the log m ...

Mixing TypeScript generic types loosely

Let's explore a simple example of typescript mixins: import { Observable, of } from 'rxjs'; class Service<TDataType> { public foo(f: TDataType): Observable<TDataType> { return of(f); } } type GConstructor<T = {}> = new ...

The element id verification only functions with optional chaining, not with type checking

While attempting to apply a gradient to a line chart, I encountered the task of accessing its canvas element. I made sure to implement a typecheck before proceeding with the canvas manipulation. However, I received an error message from Vetur stating that ...

Steps for importing vuetify/lib alongside the vuetify loader in the A-La-Carte system

When utilizing the A-La-Carte system in vuetify with vuetify-loader, I encountered a TypeScript error while trying to import vuetify/lib. I am unsure of what mistake I might be making here and would appreciate some assistance with importing this. I was re ...

Scroll to top in Angular 2 after the page finishes loading

While fetching data, I have added a loading feature. My view list includes pagination and page size. The issue arises when I change the page size and move to other pages immediately after loading, as it does not scroll back to the top. I have tried adding ...

What is the best way to handle a global path parameter in a Nest.js application?

Currently, I am in the process of constructing a rest API for a fully multi-tenant system using a single database and application. To achieve this, I have chosen NestJS as my framework of choice. My goal is to structure all modules based on the :tenantID t ...

Access a SQL database to retrieve a data value and seamlessly integrate it into an HTML document with the help of node

I am new to web development and currently facing a challenge in displaying SQL content on an HTML page. My stack includes Node.js, Express, and SQLite3. I have a folder named public containing HTML, CSS, and JS files. The objective is to retrieve a varia ...

Creating nameless entities in Typescript without resorting to type declarations

Take into account the following code snippet: type Example = { prop1: string, prop2: number } const values = ['x', 'y', 'z']; const examples = values.map<Example>((val, i) => { return { prop1: val, ...