【问题标题】:Mongoose: Unique field if it's not null or an empty string [duplicate]Mongoose:唯一字段,如果它不为 null 或空字符串 [重复]
【发布时间】:2023-04-01 03:06:01
【问题描述】:

所以,我有以下架构:

const Players = new mongoose.Schema({
    discordID: {
    type: String,
    unique: true,
    required: function () {
        return typeof this.discordID !== "string" && this.discordID !== null
    }
})

我的意思是让discordID 独一无二,但前提是它不是null""

我听说过 sparse,但它似乎没有按我的意愿工作。每次我尝试插入 2 个以上 discordID 设置为 null 的文档时都会出现重复错误(我尝试了 sparse: trueindex: {sparse: true, unique: true})。

有什么我可以做的吗?如果可能的话,我想在架构级别保留此验证。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    稀疏索引适用于省略键的文档。包含所需的discordID 并将其设置为null,该null 将被传递到数据存储中。

    https://docs.mongodb.com/manual/core/index-sparse/

    稀疏索引仅包含具有索引字段的文档的条目,即使索引字段包含空值。索引会跳过任何缺少索引字段的文档。

    在 mongoose 中将字段设置为 undefined,以便在保存之前将其删除。

    【讨论】:

    • 这个答案很有帮助,但是,我正在寻找一种方法来插入具有空值的字段。我不想在文档中缺少字段。
    • 发现了一个骗子,答案超过here...partial indexes
    猜你喜欢
    • 2016-09-11
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 2011-12-18
    相关资源
    最近更新 更多