Error in Mongoose and TypeScript: Missing property '_doc' on interface 'IEventModel'

Currently, I am enhancing my JavaScript backend programming skills through a comprehensive course that covers ExpressJS, MongoDB, and GraphQL. To make things more challenging, I have decided to reinforce my TypeScript proficiency by completing all the assignments using TypeScript.

At the moment, I am utilizing version 5.5.6 of mongoose and @types/mongoose. Below is the interface I have defined for the type of DB record:

export default interface IEvent {
    _id: any;
    title: string;
    description: string;
    price: number;
    date: string | Date;
}

Subsequently, I crafted the Mongoose Model in the following manner:

import { Document, Schema, model } from 'mongoose';
import IEvent from '../ts-types/Event.type';

export interface IEventModel extends IEvent, Document {}

const eventSchema: Schema = new Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    date: {
        type: Date,
        required: true
    }
});

export default model<IEventModel>('Event', eventSchema);

Lastly, I have formulated the subsequent resolver for a GraphQL mutation:

createEvent: async (args: ICreateEventArgs): Promise<IEvent> => {
            const { eventInput } = args;
            const event = new EventModel({
                title: eventInput.title,
                description: eventInput.description,
                price: +eventInput.price,
                date: new Date(eventInput.date)
            });
            try {
                const result: IEventModel = await event.save();
                return { ...result._doc };
            } catch (ex) {
                console.log(ex); // tslint:disable-line no-console
                throw ex;
            }
        }

The issue I am encountering is an error in TypeScript stating that "._doc" is not a property on "result". The specific error message reads as follows:

error TS2339: Property '_doc' does not exist on type 'IEventModel'.

I am struggling to identify where I might be going wrong. Despite thoroughly reviewing the documentation, it appears that all the necessary Mongoose properties are included. I may temporarily add the property to my own interface to progress with the course; however, I would greatly appreciate assistance in pinpointing the correct resolution.

Answer №1

Although this response may be tardy, it is intended to assist anyone in need of this information.

interface DocumentOutcome<T> {
    _doc: T;
}

interface IEvent extends DocumentOutcome<IEvent> {
    _id: any;
    title: string;
    description: string;
    price: number;
    date: string | Date;
}

By calling for (...)._doc, you can specify the type of _doc and allow vscode to interpret your designation accurately. Utilizing a generic declaration simplifies things, and rather than creating an interface solely for holding that property, you can integrate it within IEvent using the IEvent type.

Answer №2

When working with typescript and mongoose, I always follow a specific process.

export interface IDummy {
  something: string;
  somethingElse: string;
}

export interface DummyDocument extends IDummy, mongoose.Document {
  createdAt: Date;
  updatedAt: Date;
  _doc?: any
}

First, define interfaces for the schema and model.

const DummySchema = new mongoose.Schema<DummyDocument>({
  something: String,
  somethingElse: String,
})

Next, create the schema.

export const DummyModel = mongoose.model<DummyDocument>

Finally, export the model using the export model pattern. By following this method, you can avoid typescript errors and manually attach the _doc to the model with generics.

Answer №3

interface MongoResult {
  _doc: any
}

export default interface IEvent extends MongoResult {
    _id: any;
    title: string;
    description: string;
    price: number;
    date: string | Date;
}

Next, you will need to handle converting the _doc back to your custom IEvent object...

Answer №5

In dealing with the circular reference issue related to the _doc field, a straightforward approach is to utilize the following method. This technique effectively prevents infinite circular references by excluding itself within the child record. Furthermore, no interface extension is necessary!

export default interface IEvent {
    _doc: Omit<this,'_doc'>;
}

Answer №6

There seems to be an issue with the return type structure missing from the @types/mongoose library. This results in errors when trying to de-structure the return object because the variable is not defined in the interface signature of both document and custom types. It appears to be a bug that needs to be addressed.

To work around this issue, simply return the result itself. This will automatically return the data defined in the interface (IEvent) without including any meta data.


try {
    const result = await event.save();
                return result;
            } catch (ex) {
                throw ex;
            }

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

Creating variables in Typescript

I'm puzzled by the variable declaration within an Angular component and I'd like to understand why we declare it in the following way: export class AppComponent { serverElements = []; newServerName = ''; newServerContent = &apos ...

Error: The property 'inputItem' is not recognized on type 'EventTarget' - Utilizing Semantic-Ui, React, and Typescript

Currently, I'm utilizing React, Typescript, and Semantic UI react components. My aim is to clear the input field after successfully adding an item. While debugging, I've noticed the event.currentTarget.inputName.value which I wish to set to an em ...

I am experiencing slow load times for my Angular 2 app when first-time users access it, and I am seeking assistance in optimizing its speed

Below, you'll find a snippet from my app.ts file. I'm currently working with angular2, firebase, and typescript. I'm curious if the sluggish performance is due to the abundance of routes and injected files? The application functions smoot ...

Asking for something with no discernible purpose

I'm currently working on implementing a button that will trigger a request to display a login page. My goal is to restrict access to the login page only to project admins. To achieve this, I have their IP addresses and cross-reference them with those ...

What is the best way to query based on a nested object property in Mongoose?

const collection = [ { inner_obj: { prop: "A" } } ] Get the outer records by searching for the ones that match the value of the `prop` property within the `inner_obj` column. How can we locate the o ...

Searching for data with the Mongoose find() method in a NodeJs bot

The connection settings are specified as follows: mongoose.connect('mongodb://127.0.0.1:27017/cpfdb'); var Schema = mongoose.Schema; var definitionSchema = new Schema({ type: String, term: String, desccription: String }); var Defintion = m ...

Is there a way to transform a string property into a custom type in a TypeScript array?

I am faced with a situation where I have an interface that is extending a MongoDB document, along with some sample data that is also extending that interface. Below is an outline of the interface: export default interface IModel extends Document { _id: Obj ...

Using Express to insert data into a MongoDB database

Having trouble inserting data into MongoDB using Express as it's always storing blank. Also, no console logs are being printed: The URL I'm hitting after starting the server is http://localhost:3000/posts?title=test&link=http://test.com An ...

Create an object that may have any number of keys, but must have at least one key defined

Is there a way to accomplish this task? type Plant = "rose" | 'tulip' | 'daisy' type PlantCollection = { [p in Plant]?: number } const validPlantCollection: PlantCollection = { rose: 1, daisy: 2 } const emptyCollectionShouldBeRejec ...

searching for data within nested documents with Morphia

My document has nested data structured like this - "name" : "Naman", "gender" : "M", "occupation" : { "company" : "Honda", "designation" : "manager", "salary" : "1000000", } I want to create a Morphia query that retrieves all individuals with ...

Concocting your custom blob in Angular 2 from input may lead to data corruption

For educational purposes, I am looking to utilize the html input tag in order to select a jpeg image, extract the File Object, read it with fileReader, and use the retrieved image string (base64) to generate a new blob/file. The service successfully uploa ...

State hook variable not being properly updated within a functional component

After updating the name of an ingredient, I am looking to save this data as an ingredient with the new name: from "Milk" to "Cow's milk". I've included simple steps (1,2,3) in comments to outline the process briefly, but for clarification, assum ...

Storing and accessing formatted text in MongoDB: A comprehensive guide

I recently started working with MongoDB for my personal blog site development. I am facing an issue where the blog post, when saved as a document in the MongoDB database, loses all of its formatting and appears as a single long paragraph. I'm seeking ...

Recursive function used to update an array of objects by dynamically mapping replies to comments

I have received a collection of comments from a graphql backend structured like this: [ { "__typename": "Comment", "id": "1", "userId": "1", "postId": "1", "parentCommentId": null, ...

Save pictures on the server as files or store them in the database as a byte array

I'm currently in the process of creating a website where users can upload images for each item they have (anticipating hundreds per user). I'm torn between saving the images as bytes in the DB (mongodb) or as files on the server. Which option is ...

Tips for locating a file based on an embedded element using MongoDB with PHP

In my MongoDB database, I have the following document: Contest document: { "_id": ObjectId("502aa915f50138d76d11112f7"), "contestname": "Contest1", "description": "java programming contest", "numteams": NumberInt(2), "teams": [ { "teamname ...

Issues with the performance of a Node.js and MongoDB application hosted on AWS

Greetings to the knowledgeable community of developers, I recently took the step of deploying my node application on AWS utilizing the MEAN solution provided by Bitnami to create the necessary environment. This marks my initial foray into hosting applicat ...

What is the process for updating a value on a client site with mongodb?

I am currently using a combination of React for the front-end and Node.js with MongoDB for the back-end. In my project, I have developed a custom hook to fetch data. Below is the code snippet for this custom hook: import { useEffect, useState } from " ...

Removing a string from an array in Node.js using Mongoose's pull method

As the title suggests, I am trying to remove a string from an array using the 'pull' method. Here is my unsuccessful attempt: app.post("/accomodation-imgdelete", (req, res, next) => { Accommodation.findOneAndUpdate( { email: req.sessio ...

Rollup's watch/build feature is slow to catch up with a single change made

I have a react component library written in typescript that I am using within a monorepo with Lerna. However, I've noticed an issue when working directly in the package or watching for changes through Lerna. Whenever I make changes to the code and sa ...