Category Archives: MongoDB

Automate generation of _id for array elements in MongoDB

The great MongoDB doesn’t generate _id for array elements automatically unless it’s schema is defined separately. The below is the example to define a separate schema for the subdocuments.

const arrayElementSchema = new mongoose.Schema({...});

const mainDocument = new mongoose.Schema({
  children: [arrayElementSchema]

With the above Schema, MongoDB will generate _id for every element you insert into the “children” array.

Having _id for array elements makes it easy to find, delete and update the same. Otherwise, they have to be found by the index which will not be the same as always.