首页 > 解决方案 > 在不同的树层上有唯一的 mongodb 索引

问题描述

我有一个树状文档模型,如下图所示。是否可以为不同的图层创建唯一索引?例如,在下面的示例中,我有索引字段 1,然后是 l2 数组和 l3 数组对象中的不同索引字段。我正在尝试创建一个索引,其中所有图层的索引应该是唯一的。例如,如果我有一个索引 1,我不能在整个子文档或任何其他文档中拥有相同的索引值。我尝试为其寻找解决方案,但找不到任何解决方案。请帮我解决这个问题。提前致谢。

在此处输入图像描述

标签: mongodbmongodb-indexes

解决方案


我假设您使用的是 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。


推荐阅读