"Identifying the type of a mongoose model's instance

My goal is to develop a function that accepts a mongoose model instance as its sole parameter. In order to achieve this, I am looking to specify the Type like so:

function getModelInstance(instance: TypeToBeDetermined) {
  // actual implementation does not matter
}

Below is my code for creating the Schema and Model:

interface Product {
  name: string,
}

const productSchema = new mongoose.Schema<Product>({
  name: String,
});

const ProductModel = mongoose.model('Product', productSchema);

My attempt at achieving this functionality:

// although the type is automatically inferred, it is not practical:
//   mongoose.Model<Product, {}, {}, {}, mongoose.Document<unknown, {}, Product> & Omit<Product & { _id: mongoose.Types.ObjectId; }, never>, any>
const example1 = new ProductModel();

// no immediate error is generated, but features such as autocompletion with `example.name` do not work indicating an issue
const example2: typeof ProductModel = new ProductModel();

Update: The problem was resolved by using

const example3: InstanceType<typeof ProductModel> = new ProductModel();

If there are simpler solutions available, please share them! Thank you.

Answer №1

When working with mongoose v6.11.1 and v7.1.0, you have the option to utilize the HydratedDocument<Blog> type, which is designed to represent a fully loaded Mongoose document complete with methods, virtuals, and other Mongoose-specific features.

This provides an enhanced experience when interacting with your MongoDB data models.

To explore more about this concept, refer to this informative documentation.

I often incorporate expect-type in my workflow to validate whether the HydratedDocument<Blog> type accurately aligns with the

InstanceType<typeof BlogModel>
type.

import mongoose, { HydratedDocument } from 'mongoose';
import { expectTypeOf } from 'expect-type';

interface Blog {
  title: string,
}

const blogSchema = new mongoose.Schema<Blog>({
  title: String,
});

const BlogModel = mongoose.model<Blog>('Blog', blogSchema);

function processModelInstance(instance: HydratedDocument<Blog>) {

}

const demo3: InstanceType<typeof BlogModel> = new BlogModel();

expectTypeOf(demo3).toMatchTypeOf<HydratedDocument<Blog>>() // validation successful

// Upon inspection, we find that the expanded TS type of HydratedDocument<Blog> consists of:
// mongoose.Document<unknown, any, Blog> & Omit<Blog & {
//     _id: mongoose.Types.ObjectId;
// }, never>

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

Navigating to child components within an Angular module is currently disabled

My Project Dashboard contains 2 sub apps. ├───projects │ ├───app1 │ │ ├───e2e │ │ │ └───src │ │ └───src │ │ ├───app │ │ │ ├───form │ ...

The async/await feature in Typescript fails to trigger updates in the AngularJS view

Currently, I am utilizing Typescript 2.1 (developer version) to transpile async/await to ES5. An issue I have encountered is that when I modify any property linked to the view within my async function, the view does not automatically reflect the updated v ...

Ensuring Array Values in Mongoose Schema are Validated and Defined

Just entering the world of mongoose and looking to validate an array with specific predefined values like enum. Check out my schema below: const movieSchema = new mongoose.Schema({ language:{ type:[String], enum : ['Hindi','Englis ...

Tips for effectively simulating the formik useFormikContext function while writing unit tests using jest

I've created a simple component (shown below) that aims to fetch data from the Formik FormContext using the useFormikContext hook. However, I'm facing some challenges when writing unit tests for this component. It requires me to mock the hook, w ...

Exploring the versatility of string types in TypeScript

I'm currently working in React and have an array of pages set up like this. export const pages: Page[] = [ { path: "/", exact: true, component: PageHome }, { path: "/home2", exact: true, component: PageHome2 }, { path: " ...

Arranging items based on parent and child relationships using Angular

In my angular project, I have a dataset that needs to be sorted in a specific way. 0: {id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4} 1: {id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null} 2: {id: ...

Passing a variable from an observable to another function in Angular2: A step-by-step guide

The code snippet below is not functioning as expected. I'm attempting to pass a variable obtained from an rxjs observable function to another function, but I'm uncertain of the correct method to do so and haven't been able to find a suitable ...

The Power of TypeScript's Union Types

Provided: Reducer only accepts one of the following actions: interface ItemAction { type: 'ADD_TODO'|'DELETE_TODO'|'TOGGLE_TODO', id: number } interface QueryAction { type: 'SET_QUERY', query: string ...

Encountered an error loading resource: server returned a 404 status code while utilizing Angular framework and deploying via GitHub Pages

Currently facing an issue with my Angular website deployment on Github Pages, receiving a console error "Failed to load resource: the server responded with a status of 404 ()" at "home: 1". This error specifically seems to be related to the app.component ...

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

Combining arrays in Angular: A step-by-step guide

Below is the provided dataset: collection = [{ date: '2020-12-01', data: [{ id: 'A1', name: 'A1', date: '2020-12-01' },{ name: 'A2', date: '2020-12- ...

Mastering the Art of HTML Binding in Angular 8

I am facing a challenge in Angular 8 with displaying HTML content. The app I'm building in Angular 8 has a Flask backend that sends JSON data containing an HTML template to the frontend. My goal is to render this template in Angular. Here is the JSON ...

What steps should I take to fix the error "Unused left side of comma operator with no side effects.ts(2695)" in my React project?

import React from "react"; import { useRecoilState } from "recoil"; import { Industry, industryState } from "../atoms/industriesAtoms"; const manageIndustryData = () => { const [industryStateValue, setIndustryStateValue] ...

Utilize the class type of a method parameter as the method type for another parameter

Here's a quick example illustrating my desired functionality. // Every time, the ACL class will have a different name such as "UsersACL", etc. export class EventsACL { test(): { read: true, write: true } { } } // This function acts ...

Typescript encountering onClick function error during the build process

My current challenge involves creating a submit function for a button in my application. However, when I attempt to build the project, I encounter a typing error that is perplexing me. Despite trying various methods, I am unable to decipher how to resolve ...

Animating progress bars using React Native

I've been working on implementing a progress bar for my react-native project that can be used in multiple instances. Here's the code I currently have: The progress bar tsx: import React, { useEffect } from 'react' import { Animated, St ...

Errors occur when passing an object to the redux store in a TypeScript project due to a mismatch

I am encountering an issue where I need to pass a datum object to a redux store without triggering TypeScript errors import { TreeNodeDatum } from 'react-d3-tree/lib/types/common'; import { HierarchyPointNode } from 'd3-hierarchy'; con ...

What is the process for including an extra track in Twilio Video?

Since updating the twilio-video JS SDK from version 1.x to 2.x, I've encountered an issue when trying to add an additional device. An example of the error message is as follows: ERROR TypeError: transceiver.sender.replaceTrack(...).then(...).finally i ...

"TypeScript error: Arrays in interfaces are found to be undefined and not compatible

I'm struggling with correctly implementing the Typescript React Props syntax. In my project, I have an array of people, each of whom may have zero to many cars. There is a people container that holds all the people, each person has a car container tha ...

Is it possible to filter out certain fields from TypeORM relations or selectively include specific fields?

Within my TypeORM setup, I have established OneToMany and ManyToOne relationships that are functioning correctly. In my find function, I am able to specify certain columns from the original table using the 'select' statement like this: return a ...