Which Type to Use for ObjectId in a Mongoose Schema?

Learn about the correct ObjectId type to use in a Mongoose schema definition

If you wish to use the ObjectId type for a unique identifier in a Mongoose schema, then you should use Schema.Types.ObjectId as type in your schema definition. For example:

import { Schema } from 'mongoose';

const userSchema = new Schema({
    id: { type: Schema.Types.ObjectId, required: true },
    name: { type: String, required: true },
    // ...

Please note that this is different from how you would specify ObjectId type in a TypeScript interface.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.