【问题标题】:How to define a unique field in mongoose schema?如何在猫鼬模式中定义唯一字段?
【发布时间】:2021-09-12 12:05:20
【问题描述】:

我的架构如下:

const schema = new mongoose.Schema({
    a: {
        b: { type: String, unique: true },
        c: { type: String }
    },
    aa: {
        bb: [{
            cc: { type: String, unique: true },
            dd: { type: String }
        }]
    }
})

现在我希望 'b' 和 'cc' 字段是唯一的。 我该怎么做?

我在顶部代码的末尾添加了这段代码,但架构允许重复值。

schema.index({'a.b':1}, {unique:true})
schema.index({'aa.bb.cc':1, {unique:true})

你有什么办法解决这个问题吗?

【问题讨论】:

    标签: mongodb mongoose nosql schema unique-values


    【解决方案1】:

    这里的答案完全取决于您所说的“我希望 'b' 和 'cc' 字段是唯一的。”

    Mongoose 通过使用 unique:true 选项在该字段上创建 MongoDB 索引来实现唯一约束。

    MongoDB 通过不允许相同的值在索引中存储两次来强制执行唯一选项。

    将文档写入 MongoDB 时,它会从文档中提取索引所需的字段值,对列表进行重复数据删除,然后将值存储在索引中,并带有指向文档的指针。

    这意味着只有 1 个文档可能包含特定值,但该文档可能多次包含该值。

    例如:

    如果{i:1} 上有索引,这些示例文档将在索引中包含以下条目:

    Document Index entries
    {i:1} 1=>
    {i:[2,3,4] 2=>
    3=>
    4=>
    {i:[5,6,5,6,5]} 5=>
    6=>
    {i:[2,6]} 2=>
    6=>

    如果索引是唯一的,并且文档完全按照该顺序插入,则前 3 个文档完全可以接受,最后一个将导致重复键错误。

    【讨论】:

      【解决方案2】:

      尝试添加 dropDups,如下所示。

      const schema = new mongoose.Schema({
      a: {
          b: { type: String, unique: true, dropDups: true },
          c: { type: String }
      },
      aa: {
          bb: [{
              cc: { type: String, unique: true, dropDups: true },
              dd: { type: String }
          }]
      }
      

      })

      如果不起作用,请尝试:-

      const schema = new mongoose.Schema({
      a: {
          b: { type: String, index: { unique: true, dropDups: true } },
          c: { type: String }
      },
      aa: {
          bb: [{
              cc: { type: String, index: { unique: true, dropDups: true } },
              dd: { type: String }
          }]
      }
      

      })

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-08
        • 2018-01-21
        • 2021-09-22
        • 2022-07-20
        • 1970-01-01
        • 2017-11-20
        • 2019-05-23
        • 2021-02-23
        相关资源
        最近更新 更多