Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

How do I define a different primary key other than _id in Mongoose?


I want to define Mongoose schemas with primary keys that are not _id. The documentation says it only allows the schema options flag _id to be set to false in subdocuments. Also, I want the primary key to be a String and not an ObjectId. Is that possible at all?

Using a secondary index is an option, but not a very good one since I want to have primary keys with proper names. I also don't want to fiddle around with two different indexes when I don't need to.

This sets documentId as a secondary index but that makes the primary key useless since I want to only select by documentId and not whatever _id ends up being set to automatically.

const DocumentSchema = new Schema({
  documentId: { type: String, index: true }
})

I want to do something like

const DocumentSchema = new Schema({
  documentId: String
})

and then tell it to use documentId as the primary key.

Clarification: I specifically don't want to use the _id as a key since it has an unhelpful name and I want to use documentId as the primary key instead.


Solution

  • You could manually define _id field during the schema stage, like:

    const DocumentSchema = new Schema({
      _id: String //or number, or (increment) function,
      ...
      other_field: BSON_type,
    })
    

    Updated Nestjs

    To manually override or define _id field in schema use this example:

    /**
     * extends Document is a Mongoose Document from 'mongoose'
     * and don't forget about Nest Schema decorator
     */
    @Schema()
    export class Key extends Document { 
      @Prop({ type: String }) // also can be Number, or Decimal128
      _id: string; // number
    
      @Prop({ type: String, required: true })
      secret: string;
    }
    

    Disabling _id for subdocument in @Prop via @Prop({ _id: false })

    If you are looking for an array of embedded docs with _id example, you might wanna take a look at my other question about it.

    And add _id value to your document before the insert stage or generate it via your function, or npm module like this at the schema part. The only thing that you should make sure of, that your custom generated _id values must be unique. If they won't, mongo returns you an error, during inserting document w/o unique _id value.