1

How can I use a TS type in a mongoose schema? I have the following:

...
type Associated = {
  associatedId : string
  imei         : string
  vehicleTypeId: string
}

interface IGroup extends Document {
  ...
  associated: Associated
  ...
}

const Group = new Schema(
  {
    ...
    associated: {
      type: Associated
    },
    ...
  },
  {
    collection: 'group'
  }
)
...

But I getting an error: 'Associated' only refers to a type, but is being used as a value here.

Anthony Luzquiños
  • 739
  • 11
  • 23

1 Answers1

1

I've never attempted it myself (although I very well might after this), but searching through the internet I found basically two options to achieve similar things:

User Louay Alakkad's answer found under this link Mongoose the Typescript way...?

export interface IUser extends mongoose.Document {
  name: string; 
  somethingElse?: number; 
};

export const UserSchema = new mongoose.Schema({
  name: {type:String, required: true},
  somethingElse: Number,
});

const User = mongoose.model<IUser>('User', UserSchema);
export default User;

A library closer to achieving what you described with 1.4k stars on GitHub and it looks like it's maintained with the last commit from a week ago https://github.com/typegoose/typegoose

JKusiak
  • 33
  • 6