【问题标题】:MongoError: E11000 duplicate key error collection: ... during array update operationMongoError: E11000 duplicate key error collection: ... 在数组更新操作期间
【发布时间】:2020-10-19 14:06:32
【问题描述】:

我试图从我的架构中的 array删除一个特定值(游戏),这是代码:

User.update({ userName: user }, { $pull: { games: { _id: deleteItem } } }, function (err, val) {
    console.log(err);
});

架构:

const userSchema = new mongoose.Schema({
    userName: { type: String, index: true, unique: true },
    userPassword: String,
    games: [gameSchema]
});

错误:

MongoError: E11000 重复密钥错误集合:mountain.users 索引:games.password_1 errmsg: 'E11000 重复密钥错误集合:mountain.users index: games.password_1 dup key: { games.password: null }', [符号(mongoErrorContextSymbol)]:{} }

为什么会出现错误,我该如何解决?/从对象内部的数组中删除值的其他方法

感谢您的帮助!

【问题讨论】:

  • 请在帖子中包含以下内容:db.collection.getIndexes() 输出。
  • 也许您有另一个文档,其中games.password 不存在。可以考虑删除索引:user.games.password
  • @noam 我在所有游戏中都有密码
  • @prasad_ 我尝试对其进行控制台,但出现错误“TypeError: User.getIndexes is not a function”
  • @ORI,但是在您更新之后,这个特定游戏应该没有密码,对吧?这似乎已经发生了,有人将一个文档更新为$pull 密码远离它。

标签: node.js mongodb mongoose


【解决方案1】:

您有一个基于 games. password 数组的唯一索引。

我假设您尝试提取的游戏是数组中的最后一个游戏。并且您已经有一个带有空 games 数组的文档。

因此,这两个文档的索引值都是(null),因为它们都不存在。

sparse indexes 正是出于这个原因而存在,它允许您从 unique 行为中受益,同时只考虑具有存在值的文档。

所以基本上你必须将你的索引重新构建为一个唯一+稀疏的索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-02
    • 2022-01-05
    • 2013-02-08
    • 2012-06-07
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多