Reputation: 4296
Let's say i have a mongoose schema with the following format :
experience: [
{
title: {
type: String,
required: true
},
company: {
type: String,
required: true
},
location: {
type: String
},
from: {
type: Date,
required: true
},
to: {
type: Date
},
current: {
type: Boolean,
default: false
},
description: {
type: String
}
}
]
Experience is an array that holds objects. Now my question is, does the object that gets passed into this array get an unique ID? And why is this, it's not a separate schema it's just an object in an array. In what cases will you get an unique ID be generated.
Upvotes: 1
Views: 247
Reputation: 3529
According to the documentation: mongoose
Mongoose has two distinct notions of subdocuments: arrays of subdocuments and single nested subdocuments. And each subdocument has an
_id
by default.
So every creation of subdocument either using push
or create
adding subdocs will result in creation of unique _id
for that sub-document.
When it will not generate that _id
for those sub-documents?:
By explicitly defining { _id : false }
in the sub-schema. For example in this case:
experience: [
{
_id: false,
title: {
type: String,
required: true
},
company: {
type: String,
required: true
},
location: {
type: String
},
from: {
type: Date,
required: true
},
to: {
type: Date
},
current: {
type: Boolean,
default: false
},
description: {
type: String
}
}
]
Upvotes: 1
Reputation: 4296
I have found the answer after doing research.
The short answer is, what you see in my structure is an array of "documents"
Every document in mongoDB will have its own unique ID, this is why an ID is generated in the above example everytime a new document is inserted. This id can be used to delete or update the document in the future.
Upvotes: 0