The type 'Document<any>' cannot be assigned to type 'Pick<Pick<_LeanDocument<TicketDoc>>'

My terminal is throwing an error that seems as clear as mud:

TSError: ⨯ Unable to compile TypeScript: [orders-depl-9fbcb84ff-ngt2z orders] src/models/ticket.ts(47,5): error TS2322: Type 'Document' is not assignable to type 'Pick<Pick<_LeanDocument, "_id" | "__v" | "id" | "title" | "price" | "isReserved">, "_id" | "__v" | "id" | "title" | "price"> | QuerySelector<...> | undefined'. [orders-depl-9fbcb84ff-ngt2z orders] Type 'Document' is missing the following properties from type 'Pick<Pick<_LeanDocument, "_id" | "__v" | "id" | "title" | "price" | "isReserved">, "_id" | "__v" | "id" | "title" | "price">': title, price

It's pointing to this model file:

import mongoose from 'mongoose';
import { Order, OrderStatus } from './order';

interface TicketAttrs {
  title: string;
  price: number;
}

export interface TicketDoc extends mongoose.Document {
  title: string;
  price: number;
  isReserved(): Promise<boolean>;
}

interface TicketModel extends mongoose.Model<TicketDoc> {
  build(attrs: TicketAttrs): TicketDoc;
}

const ticketSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true,
    min: 0
  }
}, {
  toJSON: {
    transform(doc, ret) {
      ret.id = ret._id;
      delete ret._id;
    }
  }
});

ticketSchema.statics.build = (attrs: TicketAttrs) => {
  return new Ticket(attrs);
};
// Run query to look at all orders. Find an order where the 
// ticket is the ticket just found *and* the order status is *not* cancelled.
// If we find an order from that means the ticket *is* reserved
ticketSchema.methods.isReserved = async function () {
  // this === the ticket document that I just called 'isReserved' on
  const existingOrder = await Order.findOne({
    ticket: this,
    status: {
      $in: [
        OrderStatus.Created,
        OrderStatus.AwaitingPayment,
        OrderStatus.Complete
      ]
    }
  });

  return !!existingOrder;
};

const Ticket = mongoose.model<TicketDoc, TicketModel>('Ticket', ticketSchema);

export { Ticket };

I can't spot any syntax errors and this Pick type baffles me. It appears that the problem lies in ticket not being equal to this, although it should be.

Answer №1

It has been quite some time since I last came across this information. However, I came across this particular answer by user Jonathan in Udemy's questions and answers section, and I believe it offers a more effective solution compared to simply disabling TS verification:

I am not particularly fond of using ts-ignore, as Korey pointed out earlier.

I have a hunch that the issue may be related to the additional isReserved() method that was included in a Ticket document.

Therefore, instead of searching based on the Ticket document itself (this), I tried searching using the id of the Ticket document (this.id). This approach should resolve the issue.

ticketSchema.methods.isReserved = async function() {
  const existingOrder = await Order.findOne({
    ticket: this.id, // Ticket id
    status: {
      $in: [
        OrderStatus.Created,
        OrderStatus.AwaitingPayment,
        OrderStatus.Complete
      ]
    }
  })
  return !!existingOrder
}

Answer №2

Discovering this issue in TypeScript was a real eye-opener, requiring a deep understanding to resolve. Here's the workaround to eliminate the error:

// Execute a query to examine all orders. Locate an order where the 
// ticket matches the current ticket *and* the order status is *not* canceled.
// Finding such an order indicates the ticket *is* reserved
ticketSchema.methods.isReserved = async function () {
  // this === the ticket document on which 'isReserved' was just called
  const existingOrder = await Order.findOne({
    //@ts-ignore
    ticket: this,
    status: {
      $in: [
        OrderStatus.Created,
        OrderStatus.AwaitingPayment,
        OrderStatus.Complete
      ]
    }
  });

  return !!existingOrder;
};

Typically, bypassing TS checks is not recommended as they ensure type safety. However, in this case, it resolved the bizarre error that was not due to any coding mistakes but rather a TypeScript idiosyncrasy.

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

Crafting a MongoDB insertion query

Looking for some advice as a beginner in PHP and MongoDB. I've been stuck on this loop for hours with no success. This is what my input looks like: while ($currentCol<$maxCols){ $obj = array( $currentarray[0][$currentCol] => $currentarray[ ...

Ways to retrieve a URL from the assets folder

I need to establish a baseUrl for my backend requests within the assets folder. For this, I have created a server configuration file named config.json { "backendServer": { "protocol": "http", "host": " ...

Firebase data causing issues with ion-gesture recognition?

Hey there! I'm currently facing an issue with my ionic app. I added the ion-gesture to my project, but due to the ngFor loop pulling data from Firebase, the cards are unable to move. Here's a snippet of my code: <ion-card *ngFor="let po ...

Getting around using Material-UI Icons

Is it possible to utilize a Material-UI Icon for navigation using React Router Dom? I attempted the following approach without success: <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon> With buttons, I am able to use component={Link ...

What is the proper error type to use in the useRouteError() function in react-router-dom?

In my React project, I am utilizing the useRouteError() hook provided by react-router-dom to handle any errors that may arise during routing. However, I'm uncertain about the correct type for the error object returned by this hook. Currently, I have ...

Retrieve the most recent document created for each unique identifier when utilizing the $in operator

I currently have 10,000 readings (documents) stored in MongoDB along with an array of deviceIds. My goal is to retrieve the most recent document for each device using Mongoose. Here is my proposed solution: Reading.find({ "deviceId": { "$in": ...

What is the best way to enhance a react-bootstrap component with TypeScript?

Currently, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f1d0a0e0c1b420d00001b1c1b1d0e1f2f5e415f415f420d0a1b0e415e5b">[email protected]</a> and delving into the development of a customized Button ...

Tips for refining TypeScript discriminated unions by using discriminators that are only partially known?

Currently in the process of developing a React hook to abstract state for different features sharing common function arguments, while also having specific feature-related arguments that should be required or disallowed based on the enabled features. The ho ...

The Angular 6 test command using npm has encountered a failure

I've been encountering a disconnect error while attempting to run Angular test cases. With over 1500 test cases written, it appears that the sheer volume may be causing this issue. Is there a way to resolve the disconnect error when running such a lar ...

Angular form input set to disabled mode

Visit this link for code <form class="example-form"> <mat-form-field class="example-full-width"gt; <mat-label></mat-label> <input matInput placeholder="Ex. Pizza" [disabled]="filterVal ...

How to dynamically set a background image using Ionic's ngStyle

I've been trying to set a background image on my card using ngStyle Take a look at my code below: <ion-slides slidesPerView="1" centeredSlides (ionSlideWillChange)= "slideChange($event)" [ngStyle]= "{'background-image': 'ur ...

How can I conceal an element upon page load using Ionic framework?

index.component.ts initialize() { // Execute necessary functions after loading this.index.ready().then(() => { if(this.index.is('core')){ // this.menu.enable(false, 'mobileOnlyPages'); }else{ ...

Generics causing mismatch in data types

I decided to create a Discord bot using DiscordJS and TypeScript. To simplify the process of adding components to Discord messages, I developed an abstract class called componentprototype. Here is how it looks (Please note that Generators are subclasses li ...

Issue with event.stopPropagation() in Angular 6 directive when using a template-driven form that already takes event.data

I am currently developing a citizenNumber component for use in forms. This component implements ControlValueAccessor to work with ngModel. export class CitizenNumberComponent implements ControlValueAccessor { private _value: string; @Input() place ...

Passing RxJs pipes as a parameter

Is there a way to pass pipes as parameters? For example: var mypipes = [ pipeA(() => { alert("a"); }), pipeB(() => { alert("b"); }) ...

In MongoDB, how can I retrieve the exact hour leading up to the most recent one?

How can I retrieve the second latest full hour? For example, if the current time is 15:30, I want to get 14:00 by removing the minutes and then subtracting an hour. This is how I want to display the date: // If the current time is 15:46 "period" ...

What might be the underlying reason for Chrome displaying a net::ERR_FAILED error when attempting to make a request from a Vue frontend to a C# API using Axios?

I have a C# Backend+API that I interact with from my Vue Application using axios to make requests. In the C# code, there is an endpoint that looks like this: // GET: api/Timezone public HttpResponseMessage GetTimezoneData() { ...

Unable to extract a string from an object in Node.JS

I am attempting to connect my MongoDB database using Node.js with Express.js. I have tried creating a schema and parsing objects into JSON, but it doesn't seem to be working. Below is the content of my index.js file: var express = require('expre ...

What could be causing the Express error when this.props.param.match.id is coming up as undefined?

I am currently delving into the world of Express.js, attempting to understand how to utilize it effectively. However, I am encountering an issue where I am unable to retrieve an id value from this.props.match.params. Here is how my express route is set up ...

What steps can be taken to address the InvalidPipeArgument error when working with dates?

When attempting to format a date in a specific way using the pipe date, I encountered an error: Uncaught Error: InvalidPipeArgument: 'Unable to convert "25/01/2019" into a date' for pipe 'e' at Xe (main.fc4242d58c261cf678ad.js:1) ...