【问题标题】:How can I solve a "MongoError: E11000 duplicate key error collection" error in Mongo?如何解决 Mongo 中的“MongoError:E11000 重复键错误收集”错误?
【发布时间】:2022-04-19 03:50:50
【问题描述】:

我已经为一个新项目创建了一个新的 Mongo 集合,但是当我尝试创建一个新用户时,我收到以下错误:

MongoError: E11000 duplicate key error collection: GestorMedico.users index: username_1 dup key: { username: null }

我的用户架构如下:

const { Schema, model } = require("mongoose");

const userSchema = new Schema({
    nombreEmpresa: {
        type: String,
        unique: true,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    telefono: {
        type: String,
        required: true
    },
    contraseña: {
        type: String,
        required: true
    }
}, {
    timestamps: true,
    versionKey: false
});

module.exports = model("Users", userSchema);

我的功能如下:

userCtrl.createUser = async (req, res) => {
    const newUser = new User(req.body);
    
    newUser.contraseña = await crypt.encryptPassword(newUser.contraseña);
    
    await newUser.save();
    
    res.status(200).json({
        status: "OK",
        message: "User created"
    });
};

我的收藏看起来像:

我已经重用了我的一个旧项目的后端,它在架构中有一个“用户名”。

【问题讨论】:

  • 您似乎没有 username 作为架构的一部分,并且您已在其上创建了索引。请更改架构或删除用户名上的索引。

标签: javascript node.js mongodb mongoose


【解决方案1】:

当您尝试保存的唯一字段(索引)而数据库中已有另一个字段(索引)时,将引发错误 E11000。

由于该字段似乎是在 userSchema 中不可见的用户名,我假设您的数据库中仍然存在该索引。

在页面上的 mongo Compass 中,您从中截取了屏幕截图,转到“索引”选项卡,刷新并删除用户名索引以防万一。

如果这不能解决它继续通过代码打印出索引并在那里检查,如果有一个你不想使用db.collection.dropIndex() 删除它。 Docs here

还要确保在您的 req.body 中转移了 nombreEmpresa 字段,因为当您要保存文档时需要它。

我希望能解决它;)

【讨论】:

    【解决方案2】:

    您将用户名索引设置为唯一属性,因此您必须使用它:

    db.user.dropIndex()
    

    或者当您在指南针的用户集合中时,您可以从集合Shot 上方的选项卡中删除您的索引

    【讨论】:

      【解决方案3】:

      这个问题至少在我们做 unique: true 时会出现,如果你删除这个选项错误仍然存​​在,我通过删除集合解决了这个问题。 如果您再次想要相同的集合,您可以插入文档,并且将创建相同的集合而不会出现此错误。

      谢谢!

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2018-01-04
      • 2019-09-10
      • 2021-09-02
      • 2018-07-29
      • 2019-01-05
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多