Home > Software engineering >  How to change, customize, Mongoose default _id property?
How to change, customize, Mongoose default _id property?

Time:11-02

I have the following schema:

const { ObjectId } = Schema.Types

const Account = new Schema({
    name:           { type: String, required: true },
    accountId:      { type: String, required: true },
    piracicaba:     [{ type: ObjectId, ref: 'Piracicaba'}]
})

I know that by default MongoDB creates an _id property, but I would like to make accountId my default ID instead. Also, I would like to change that default generated string to a custom one.

How could I do that?

I have tried to change the accountId type to ObjectId:

const { ObjectId } = Schema.Types

const Account = new Schema({
    name:           { type: String, required: true },
    accountId:      { type: ObjectId },
    piracicaba:     [{ type: ObjectId, ref: 'Piracicaba'}]
})

But then when I try to store my customized ID mongoose throws BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer.

My customized ID is from Oracle Cloud Account and it looks like this: ocid1.test.oc1..<unique_ID>EXAMPLE-compartmentId-Value

CodePudding user response:

If you include an _id field in your schema definition, when you insert a document you must supply it with your own manually generated _id. If you don't, the document will not get inserted.

Alternatively, if you do not include an _id field in your schema definition, Mongoose will create this for you automatically, when the document is inserted, and it will be of type ObjectId (which is the default way that MongoDB sets the _id field on documents).

  • Related