mongoose: Cannot specify a custom index on `_id` for model name "SchemaName", MongoDB does not allow overwriting the default `_id` index

Viewed 3679

So I just tried to custom _id in mongoose schema like this :

const userSchema = new mongoose.Schema({
        _id: {
            type: String,
            required: true,
            unique: true
        },
        ...
        ...
})

and get this message : mongoose: Cannot specify a custom index on _id for model name "SchemaName", MongoDB does not allow overwriting the default _id index.

The thing is, everything's fine. I can insert the data and select it like normal. Should I do something about that message?

2 Answers

I think the error is appearing as you are trying to define required:true and unqiue:true, as _id will already have this in place, that is you cannot have _id to have non-unqiue value even if the condition from mongoose is not there and it is always required. Try dropping these two constraints and just setting the the type:String and this message should disappear

Adding _id: false to the options ,{} (second argument) does the trick:

const userSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    }, { _id: false })

That tells Mongo you don't want _id to be automatically created by Mongo/Mongoose. Because you want to do it yourself, your own way.

In fact, if you are not using _id, you don't even need to mention it in the first argument. Only the second is important ({ _id: false }):

const userSchema = new mongoose.Schema({
    code:    { type: String, required: true, unique: true },
    name:    { type: String, required: true },
    another: { type: Number, required: false },
  }, { _id: false })
Related