You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB E11000重复键错误:Item集合title可重复需求异常

问题描述

我有两个Mongoose集合:Item和Mess,Schema定义如下:

Item Schema

const mongoose = require("mongoose");

const ItemSchema = mongoose.Schema(
  {
    title: {
      type: String,
      required: [true, "Item name required"],
      unique: false,
      minLength: [4, "Cannot be less than 4 characters"],
      maxLength: [40, "Cannot be greater then 40 characters"],
    },

    units: {
      type: Number,
      required: [true, "Item units required"],
      min: [0, "Invalid value"],
    },
    mess: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Mess",
      required: [true, "Mess name required"],
    },
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model("Item", ItemSchema);

Mess Schema

const mongoose = require("mongoose");
const MessSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true,
    uppercase: true,
  },
}, {
  timestamps: true,
});
module.exports = mongoose.model("Mess", MessSchema);

尝试插入两条title相同但mess不同的数据时:

db.items.insertMany([{
    "title": "chicken qorma",
    "units": 160,
    "mess": "63dde5547cf24f27a81cc82c"
},
{
    "title": "chicken qorma",
    "units": 160,
    "mess": "63dde53a7cf24f27a81cc829"
}])

出现E11000重复键错误:

E11000 duplicate key error collection: MessIT.items index: name_1 dup key: { name: null }

我需要title字段允许重复,但尝试多种方案都没解决问题,求帮助。

解决方案

错误提示里的name_1索引是问题核心——你的items集合上存在一个针对name字段的唯一索引,但当前的Item Schema里根本没有定义name字段。插入数据时,MongoDB会给不存在的字段默认赋值null,两次插入的name都是null,触发了唯一索引的冲突。

解决步骤:

  • 先查看items集合的所有索引,确认name_1索引存在:
    db.items.getIndexes()
    
  • 删除这个多余的name_1索引:
    db.items.dropIndex("name_1")
    
  • 再次执行插入操作,即可成功插入title相同但mess不同的数据。

补充说明:这个索引大概率是之前的Schema版本里定义过name字段并设置了unique: true,后来修改Schema时移除了该字段,但数据库里的索引没有自动删除,导致出现这个问题。

内容的提问来源于stack exchange,提问作者Mian Usama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 16:15:44