Search code examples
mongodbmongoosemongoose-schema

Mongodb: which datatype must be used in Mongoose schema to store null and ObjectId of the document


The schema I am using for category collection looks like:

{
  name: { type: String, required: true },
  parent: { type: mongoose.Schema.Types.ObjectId, required: true }
}

Now, for all level-1 categories, I want to store parent as null and for level-2 and so on will be storing ObjectId of the parent document. How to define this condition in schema? I can not use type String as it will not allow me to map to parent document whenever required. Any other solution for achieving this?


Solution

  • {
      name: { type: String, required: true },
      parent: { type: mongoose.Schema.Types.ObjectId, required: true, default: null }
    }
    

    Setting the default key as null might help... if value not inserted it defaults to null.