假设我有一个具有以下格式的 Mongoose 模式:
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
}
}
]
经验是一个存放对象的数组。现在我的问题是,传递给这个数组的对象是否有一个唯一的 ID?为什么会这样,它不是一个单独的模式,它只是数组中的一个对象。在什么情况下你会得到 生成一个唯一的 ID。
最佳答案
根据文档:mongoose
Mongoose has two distinct notions of subdocuments: arrays of subdocuments and single nested subdocuments. And each subdocument has an
_id
by default.
因此每次使用 push
或 create
adding subdocs 创建子文档 都会导致为该子文档创建唯一的 _id
。
什么时候它不会为那些子文档生成那个_id
?:
通过在子模式中显式定义 { _id : false }
。例如在这种情况下:
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
}
}
]
关于javascript - 什么情况下mongo会生成唯一ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58167023/