Mongoose + Typescript -> Exporting model interface Mongoose + Typescript -> Exporting model interface mongoose mongoose

Mongoose + Typescript -> Exporting model interface


Try:

interface UserDocument extends IUser, Mongoose.Document {   _id: string;}

It will resolve the conflict between IUser._id (string) vs Mongoose.Document._id (any).

Update:

As pointed out in comments, currently it gives a incompatible override for member from "Document", so another workaround must be used. Intersection types is a solution that can be used. That said, the following can be done:

type UserDocument = IUser & Mongoose.Document;

Alternatively, if you do not want UserDocument anymore:

// Modellet Users = Mongoose.model<IUser & Mongoose.Document>('User', userSchema);

It is worth noting that there is a side effect in this solution. The conflicting properties will have the types intersected, so IUser._id (string) & Mongoose.Document._id (any) results in UserDocument._id (any), for example.


I just had this exact issue, where I wanted to keep the User interface properties as separate from Mongoose as possible. I managed to solve the problem using the Omit utility type.

Here is your original code using that type:

import { Document, Model, ObjectId } from 'mongoose';export interface IUser {  _id: ObjectId;  name: string;  email: string;  created_at: number;  updated_at: number;  last_login: number;}export interface IUserDocument extends Omit<IUser, '_id'>, Document {}export interface IUserModel extends Model<IUserDocument> {}


try this:

const UserSchema: Schema = new Schema(  {   ..  });type UserDoc = IUser & Document;export interface UserDocument extends UserDoc {}// For modelexport interface UserModel extends Model<UserDocument> {}export default model<UserDocument>("User", UserSchema);