Which Type to Use for Mongoose ObjectId in a TypeScript Interface?

If you wish to specify Mongoose ObjectId as a type for a TypeScript interface property, then you should use Types.ObjectId as type. For example:

import { Types } from 'mongoose';

interface User {
  id: Types.ObjectId;
  name: string;
  // ...
}

const userSchema = new Schema<User>({
    // ...
});

Please note that this is different from how you would specify ObjectId as a type in a Mongoose schema definition.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.