MongoDB is a NoSQL database that stores data as
Mongoose, on the other hand, is an
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
.
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.
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.
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
.
RELATED TAGS
CONTRIBUTOR
View all Courses