mongodb - 在不同的树层上有唯一的 mongodb 索引
问题描述
我有一个树状文档模型,如下图所示。是否可以为不同的图层创建唯一索引?例如,在下面的示例中,我有索引字段 1,然后是 l2 数组和 l3 数组对象中的不同索引字段。我正在尝试创建一个索引,其中所有图层的索引应该是唯一的。例如,如果我有一个索引 1,我不能在整个子文档或任何其他文档中拥有相同的索引值。我尝试为其寻找解决方案,但找不到任何解决方案。请帮我解决这个问题。提前致谢。
解决方案
我假设您使用的是 NodeJs 和 Mongoose,因为您没有指定。您可以通过在嵌套对象中使用不同的模式来获取每个级别的 ObjectId,如下例所示。
const level2Schema = new Schema({
unit: {
type: String,
required: true
},
price: {
type: Number,
required: true
}
});
const level1Schema = new Schema({
feildx: {
type: String,
required: true
},
anyNameArray: {
type: [level2Schema],
required: true
}
});
var MainSchema = new Schema(
{
field1: String,
field2: String,
anyNameArray: {
type: [level1Schema],
default: [],
required: true
},
},
{ timestamps: true }
);
这将为每个嵌套文档创建一个唯一的 ObjectId。
推荐阅读
- linux - Laravel 护照 API 认证失败
- tensorflow - 使用 tensorflow 时 __enter__ 出现 AttributeError 问题
- android - 通知的 setDeleteIntent 中的待处理意图永远不会调用 BroadcastReceiver
- java - 与 Spring Data JPA 结合使用时,事务注释不会使我的代码原子化。请建议
- javascript - 为什么 fetch 会返回“TypeError:无法获取”而不仅仅是“无法获取”?
- iot - 带有 PulsesensorPlayground 的 ESP32
- java - 在一段文本中嵌入字体,而不是全部
- instagram-graph-api - Instagram API 数据与 Instgram Insights 数据不匹配
- javascript - 使用正则表达式将“边距”替换为 HTML 标记内的填充
- python - 如何为我的自定义记录器设置与 Gunicorn 记录格式相同的记录格式