Home > database >  How to implement "equals" for interface from mongodb?
How to implement "equals" for interface from mongodb?

Time:05-11

export interface IHealthPlanCard {
    _id: string,
    statusId: string;
}

const cards: IHealthPlanCard[] = await healthPlanCardsCollection.find(...)
cards.filter(card => card.statusId.equals(cardStatusId))

In that case it shows me error: Property 'equals' does not exist on type 'string'.ts(2339)

I can't write something like that:

export interface IHealthPlanCard {
    _id: string,
    statusId: string | eqauls;
}

CodePudding user response:

If you are using MongoDB (or mongoose) and dealing with ObjectIds, you should always use the ObjectId type instead of string:

import { ObjectId } from "mongodb"
// import { Types } from "mongoose"

export interface IHealthPlanCard {
  _id: string,
  statusId: ObjectId;
}

const cards: IHealthPlanCard[] = await healthPlanCardsCollection.find(...)
cards.filter(card => card.statusId.equals(cardStatusId))

This will only work if you defined your schema to use ObjectId instead of string.

Now your ObjectIds will have the .equals() method.

  • Related