【问题标题】:How to add a new field to mongodb collection and make it unique?如何向 mongodb 集合添加新字段并使其独一无二?
【发布时间】:2019-09-29 02:31:45
【问题描述】:

我有一个包含多个现有数据的 mongodb 集合,现在我想在同一集合中添加新字段,同时新字段需要是唯一字段。

我将 nodejs 与猫鼬一起使用。

以下是我当前的架构。

const user = new mongoose.Schema({
    username: { type: string, required: true},
    token: { type: String, required: true }
});

现在下面是我的新架构

const user = new mongoose.Schema({
    username: { type: string, required: true},
    token: { type: String, required: true },
    nickname: { type: String, required: true }
});

user.index({ "nickname": 1}, { "unique": true });

因为当我运行代码时它有现有数据,所以它给了我以下错误。

E11000 duplicate key error collection: ourcompany.users index: nickname_1 dup key: { : null }

我相信当新字段被创建时,它将被归档为空值。由于新字段是唯一的,因此不允许多个空值。

我有这个document 的场景,但我不明白要遵循什么步骤。 请告知我需要填补的空白。

提前致谢

【问题讨论】:

  • 您的 mongo 版本是否 >= 3.2?您的参考“文档”要求指导您使用类似 partialFilterExpression: { nickname: { $exists: True } } } 的版本 >= 3.2。查看partialFilterExpression
  • 谢谢,我会调查一下

标签: node.js mongodb mongoose


【解决方案1】:

使用sparse: true 将其设为

    const user = new mongoose.Schema({
    username: { type: string, required: true},
    token: { type: String, required: true },
    nickname: { type: String, required: true,sparse: true }
});

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2021-06-26
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 2015-09-06
    • 1970-01-01
    相关资源
    最近更新 更多