How to disable MongoDB from creating ids for subdocuments

MongoDB and Mongoose

MongoDB is a NoSQL database that stores data as JSONJavascript Object Notation documents. NoSQL databases are used as an alternative to traditional relational databases.

Mongoose, on the other hand, is an ODMObject Data Modeling library for MongoDB and Node.js.

There are times when we need to create subdocuments within a document. By default, subdocuments are created with their own id. However, in some cases, we want do not want these documents to have an id.

Mongoose allows you to restrict subdocuments so that they do not have an id.

Structuring your schema

First, let’s create a schema through Mongoose, as shown below:

// import mongoose
var mongoose = require("mongoose");
// creating a schema with mongoose
var schema = mongoose.Schema({
// schema content
})

In the code above, we created a schema by importing Mongoose and using the mongoose.Schema({}) constructor object. The next step is to create a subschema in the schema document.

Creating a subschema

A subschema represents a document inside another document. They are a way to structure a document to have subdocuments.

The below code adds a subschema inside of the previously defined schema:

// import mongoose
var mongoose = require("mongoose");
// create subschema
var subSchema = mongoose.Schema({
// your subschema content
});
// add subschema to main schema
var schema = mongoose.Schema({
// schema content
subSchemaCollection : [subSchema]
});

The above implementation will cause any subdocument that is created to have its own id.

Note: A collection is referred to as a table in a relational database like SQL.

Disabling a subdocument’s id

To restrict subdocuments from having their own id, you will have to add the option {_id : false } to the subschema, as shown below:

var subSchema = mongoose.Schema({
// your subschema content
},
// prevent any subdocuments from having an id
{ _id : false }
);

This way, any subdocuments created will not have an id.

Free Resources