【问题标题】:Ensure property in document is unique only if they have the same value of another property仅当文档中的属性与另一个属性具有相同的值时,才确保它们是唯一的
【发布时间】:2021-10-17 20:37:32
【问题描述】:

假设我有这样的架构:

const MySchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
    },
    nonce:{
        type: Number,
        required: true,
    }
});

如果 userId 相同,我如何确保 nonce 是唯一的?但是具有不同 userId 的文档可以具有相同的 nonce?

【问题讨论】:

    标签: mongodb mongodb-query nonce


    【解决方案1】:

    您可以创建唯一的复合索引,例如:

       db.collection.createIndex({userId:1 , nonce:1 },unique: true)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-17
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2016-06-06
      相关资源
      最近更新 更多