François MILHET
François MILHET

Reputation: 31

How to type array of mongoose ObjectID in typescript

I'am having an issue with the typing in TypeScript and mongoose schema. I have the following model for a user :

export interface IUser extends mongoose.Document {
    firstname: string;
    lastname: string;
    email: string;
    password?: string;
    lang: string;
    color: string;
    roles: IRole[];
    labs: ILab[];
}

export const UserSchema = new mongoose.Schema({
    firstname: {
        type: String,
        required: [true, 'Firstname required']
    },
    lastname: {
        type: String,
        required: [true, 'Lastname required']
    },
    email: {
        type: String,
        required: [true, 'Email required']
    },
    password: {
        type: String,
        required: [true, 'Password required']
    },
    lang: {
        type: String,
        required: [true, 'Lang required']
    },
    color: {
        type: String,
        required: [true, 'Color required']
    },
    roles: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Role'
        }
    ],
    labs: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Lab'
        }
    ]
});

The thing is that i want to do a query to retrieve all the users that match a specific lab ID so I mad this :

User.find({ labs: { $in: req.params.id } })

But I have an error with typecript because the find is actually on ObjectId array, but in the interface relate to ILab[].

The only way i found is to make the query as Any but as you may know it is not ideal to use any. Would be nice if anyone have a hint on that ?

Upvotes: 3

Views: 2907

Answers (1)

shopkeeper
shopkeeper

Reputation: 309

Maybe just:

import { Schema } from "mongoose";
interface IUser extends mongoose.Document {
  ...
  labs: [{ type: mongoose.Schema.Types.ObjectId, ref: "Lab" }];
}

I had the same problem and I fixed it this way.

Upvotes: 4

Related Questions