【问题标题】:How to make a mongoose schema attribute unique after the schema is instantiated (already contains data)模式实例化后如何使猫鼬模式属性唯一(已包含数据)
【发布时间】:2021-11-13 13:34:00
【问题描述】:

我有一个猫鼬模式,

const loggerSchema = mongoose.Schema(
    {
        // Other ...
        cluster: {
            type: String,
            required: true,
        },
        // ...
    }
)

它目前充满了大量数据。我想修改cluster属性如下

const loggerSchema = mongoose.Schema(
    {
        // Other ...
        cluster: {
            type: String,
            required: true,
            unique:true
        },
        // ...
    }
)

如何在不丢失任何数据(在数据库中)的情况下实现这一目标?前提是所有现有数据都包含 cluster 属性的唯一值。

【问题讨论】:

标签: node.js mongodb mongoose schema unique


【解决方案1】:

如果您确定 cluster 没有重复值,您可以按照您提到的那样立即更改您的架构(如果有重复,它将无法在 cluster 上创建唯一索引)。
阅读有关独特选项 here 的更多信息。

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 2015-09-20
    • 2021-05-10
    • 2015-02-23
    • 2018-06-08
    • 2022-01-12
    • 2011-11-14
    • 2021-10-01
    • 2021-09-12
    相关资源
    最近更新 更多