Typescript and Mongoose Schema - Common Design Mistakes

I am encountering two issues while defining a schema using mongoose and typescript. Below is the code snippet I'm having trouble with:

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

export interface IApplication {
    id: number;
    name: string;
    virtualProperty: string;
}

interface IApplicationModel extends Document, IApplication {} //Issue 1

let ApplicationSchema: Schema = new Schema({
    id: { type: Number, required: true, index: true, unique: true},
    name: { type: String, required: true, trim: true },
});
ApplicationSchema.virtual('virtualProperty').get(function () {
    return `${this.id}-${this.name}/`; // Issue 2
});
export const IApplication: Model<IApplicationModel> = model<IApplicationModel>("Application", ApplicationSchema);

Firstly:

  • Issue 1 arises in this line:

interface IApplicationModel extends Document, IApplication {}

The Typescript compiler is reporting:

error TS2320: Interface 'IApplicationModel' cannot simultaneously extend types 'Document' and 'IApplication'.
  Named property 'id' of types 'Document' and 'IApplication' are not identical.

How can I modify the definition of the id property to resolve this?

  • Issue 2 lies within the inner function (getter for virtualProperty):

    return `${this.id}-${this.name}/; // Issue 2

The Error message indicates:

error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.

What is the correct way to define the type of this in this context?

Answer №1

Issue #1: The IApplicationModel interface extends the Document and IApplication interfaces, which both have a property named id but with different types (any and number respectively). This ambiguity confuses TypeScript, so it's essential to redeclare the id property in IApplicationModel with the correct type specified. (Consider why create a separate IApplication interface instead of directly extending Document in IApplicationModel with all necessary properties.)

Issue #2: Simply define the special this parameter inside the function as illustrated below.

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

export interface IApplication {
    id: number;
    name: string;
    virtualProperty: string;
}

interface IApplicationModel extends Document, IApplication {
    id: number;
}

let ApplicationSchema: Schema = new Schema({
    id: { type: Number, required: true, index: true, unique: true},
    name: { type: String, required: true, trim: true },
});
ApplicationSchema.virtual('virtualProperty').get(function (this: IApplicationModel) {
    return `${this.id}-${this.name}/`;
});
export const IApplication: Model<IApplicationModel> = model<IApplicationModel>("Application", ApplicationSchema);

Answer №2

To resolve issue 2, simply specify this as any: .get(function (this: any) {}); and the problem will be solved.

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

Upon installation, the extension that replaces the new tab fails to detect the index.html file

edit: Check out the Chrome Extension here Edit 2: It seems that the recent update containing the index.html file was not published due to Google putting it under revision. Apologies for forgetting to include the index.html file in the upload zip, as I ...

Looking to retrieve the raw HTTP header string in Node.js using express.js?

Currently, I am utilizing Node.js and express.js for my work. The project I am currently working on requires me to access the raw strings of the HTTP headers (charset and accepted). In express.js, there is a function available that can provide the charset ...

Discover the URLs that are connected to my iframe/widget

I've crafted a widget.html page that includes a "Powered by Example.com" box or widget. Additionally, I've implemented an HTML iframe that points to this specific page (widget.html) on my website. <iframe src="http://example.com/widget.html"& ...

Converting <reference path/> directive to ESM import: A step-by-step guide

As I embark on developing a TypeScript application, I've reached the realization that I am not a fan of using the <reference path /> triple-slash directive. Instead, I prefer utilizing import 'something'. However, every time I attempt ...

A guide on adding an onClick listener to a span element dynamically and then saving it to MongoDB

I have been attempting to add an onClick event within a span tag as shown below, with the goal of storing it in MongoDb. However, my event does not seem to be saving and is automatically removed. When I retrieve data from the database, it is not present. H ...

How can I retrieve an array of data from Firebase Firestore using React Native?

I have been working on fetching Array data from Firebase Firestore. The data is being fetched successfully, but it is all displaying together. Is there a way to fetch each piece of data one by one? Please refer to the image for a better understanding of ...

Unable to display PHP response in a div using AJAX - issue persisting

Hey there! I'm currently working on a project where I want the form submission to load a response into a div without refreshing the page. I've looked at various examples of ajax forms with PHP online, but haven't been able to solve my issue ...

Create a JSON file on the fly

I am in need of performing a post request using a JSON file. The current structure of the JSON is as follows: { "compositeRequest" : [{ // Account "method" : "POST", "url" : &quo ...

What is the best way to fetch data before a component is rendered on the screen?

I am facing an issue with fetching data from a local server in Node. When I try to render the component, the array 'users' from the state appears to be empty, resulting in no users being displayed on the screen as intended. What's strange is ...

Divide a JSON dataset into two distinct JSON files and incorporate them within the code

My JSON file structure is as follows: { "rID": "1", "rFI": "01", "rTN": "0011", "rAN": "11", "sID&quo ...

A unique Javascript feature that switches the text on various buttons

As someone who is relatively new to Javascript and web development, I am currently working on a project that involves creating multiple text areas for users to input and save text. Each text area is accompanied by a button with a unique ID that functions a ...

Structural engineering for massive webpage

Currently I am in the process of building a large page using AngularJS. As I plan out the architecture for this page, I am debating which approach would be most effective. The page consists of 3 distinct blocks with various functionalities, but the prima ...

How to automatically insert a page break after a certain string in an array using JavaScript

I've created a code that is intended to implement page breaks after a specific number of new lines or words. I have defined an array that indicates where these breaks should occur within my element. In the example provided in my jsFiddle, you can see ...

Utilize Ajax to transfer an image from an input form to a PHP script

I am currently working on a basic HTML page that includes an image upload form. Here is the code for the form: <input type='file' id='image_uploaded' accept='image'/> <input type='submit' id="upload_image"/ ...

I seem to be having an issue with the decimal point on my calculator - I only want to see one dot

Only need one dot for the calculator to function properly. The current situation with multiple dots is causing confusion. I intend to address other aspects of the code later, but I'm currently struggling with this issue. function dec(d) { let ...

How to create a thumbnail hover effect with CSS3 and javascript, overcoming the z-axis issue

Currently, I am working on creating a set of thumbnails that enlarge when hovered over. The initial setup achieves the zoom effect using CSS3 transform:scale and ease-in-out. However, the issue is that the enlarged images overlap each other due to sharing ...

Struggling with implementing nested for loops

I am struggling to find a solution for this issue. I need to compare the content of two arrays with each other. If they are exactly the same, I want to execute the if statement; otherwise, I want the else statement to be executed. The current setup is ca ...

Strange response received from Stack Overflow API request

Having some issues with the code I'm using to call the Stack Overflow API: var request = require('request'); var url = 'http://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=node.js&intitle=node.js&sit ...

react-vimeo not firing onPause and onPlay events

I am facing an issue with triggering props when playing a Vimeo video on my webpage. Here's a snippet of my code: import Vimeo from '@u-wave/react-vimeo'; const handleVimeoProgress = (data: any) => { console.log('Progress:' ...

Tips for maintaining the size of an object while resizing a window

My circles are designed to increase in width at regular intervals, and once they reach a certain scale, they disappear and start over. However, every time I resize the screen or zoom in and out, the circle gets distorted into an oval or stretched object. H ...