【问题标题】:MongoDB Unique Index on array element across documents (not across nested document)跨文档数组元素的 MongoDB 唯一索引(而不是跨嵌套文档)
【发布时间】:2020-11-08 04:28:58
【问题描述】:

我有一个架构如下:

Schema = mongoose.Schema    
User= new Schema
    { name: String,
     phones: [
    {
      confirmed: {
        type: Boolean,
        default: false
      },
      number: {
        type: String,
        unique: true
      }
  ]}  

这应该不允许创建 2 个具有相同电话号码的文档。我知道索引在数组元素中不能是唯一的,所以我可以在嵌套文档中拥有 1 个具有 2 个相同数字的文档,但我不希望 2 个文档具有相同的数字。未创建索引。我检查了可能不允许创建索引但没有创建索引的现有重复文档。我尝试用

在地图集创建索引

{ "phones.number": 1 }, {unique:true}

它根本不会创建它

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    为此,您需要更改一些内容。

    首先,您的架构必须是这样的index

    number: {
      type: String,
      index: true, // <-- This line
      unique: true
    }
    

    并且,在您的连接选项中添加useCreateIndex: true。例如,我有:

    const mongooseOpts = {
        useNewUrlParser: true,
        useFindAndModify: false,
        useUnifiedTopology: true,
        useCreateIndex: true //<-- This line
    };
    
    await mongoose.connect(uri, mongooseOpts);
    

    然后,当您尝试添加重复号码电话时,将引发错误。

    BulkWriteError: E11000 重复键错误 dup key: { : "1" }

    通过这两个步骤,如果仍然不起作用,请尝试删除 collection 并重新创建。

    【讨论】:

    • 嗯,没用。明天我会尝试删除收藏并通知您。非常感谢
    猜你喜欢
    • 2016-03-15
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多