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

Node.js REST API仅能创建一条记录,再次请求触发重复键错误

问题

我构建了一个仅包含POST端点的简单API,该接口通过req.body提交数据。首次请求可正常创建记录,但再次请求时会触发如下错误:

{
    "index": 0,
    "code": 11000,
    "keyPattern": {
        "centralEmail": 1
    },
    "keyValue": {
        "centralEmail": null
    }
}

奇怪的是,centralEmail字段完全未在当前模型或路由中定义,全程无相关引用。以下是我的Schema和API代码:

Schema代码

const mongoose = require("mongoose")

//this just regulates the roles and their data connected to them. Will build out with more aux data support

// //RolesPositionSchema
const RolesListingSchema = new mongoose.Schema(
    {
    role:{type:String, required: true, default: ""},
    companyListing:{type:String, required: false, default: ""},
    companyID:{type:String, required: false, default: ""},
    dateListing:{type:String, required: false, default: ""},
    status: {type: String, required: false},

    finalFormat:{type:String, required: false, default: ""},

    listingScore:{type: Number},
    companyEmail:{type:String},

    selectedStyle:{type:String, required: false, default: ""},
    selectedLocation:{type:String, required: false, default:""},
    selectedIndustry:{type:String, required: false},

    optionalMinSalaryRange:{type:String, required: false, default: ""},
    optionalMaxSalaryRange:{type:String, required: false, default: ""},
    optionalQuals:{type:String, required: false, default: ""},

    selectedInterview1:{type:String, required: false, default: ""},
    selectedInterview2:{type:String, required: false, default: ""},
    selectedInterview3:{type:String, required: false, default: ""},

    optionalSkills:{type:[String], required: false, default: []},

    optionalPerks:{type:[String], required: false, default: []},

    optionalWFH:{type:String, required: false, default: ""},

    optionalQuals:{type:[String], required: false, default: []},

    //
    lookingFor:{type:[String], required: false, default: []},
    dailyResponsibilites:{type:[String], required: false, default: []},
    FAQS:{type:[String], required: false, default: []},

    //
    requiredFields:{type:[String], required: false, default: []},

    },
);

module.exports = mongoose.model("RoleListings", RolesListingSchema)

API代码

//CREATE A ROLE DESC
//Implement new roles
router.post("/", async (req,res)=>{
// router.post("/", verifyTokenAndAdmin, async (req,res)=>{
    const newRole = new Role(req.body)

    try{
        const savedRole = await newRole.save();
        res.status(200).json(savedRole)
    }catch(err){
        res.status(500).json(err)
    }
})
解决方案

这个错误是MongoDB唯一索引冲突导致的,核心原因:

  • RoleListings集合曾经存在过centralEmail字段,并且被设置了唯一索引。即使现在Schema中删除了该字段,MongoDB集合上的索引不会自动消失。
  • 插入新文档时,未定义的字段默认值为null,而唯一索引不允许多个文档的该字段值为null,因此首次插入成功(第一个null值),再次插入就触发冲突。

解决步骤:

  1. 连接到MongoDB数据库,定位到RoleListings集合
  2. 查看集合的所有索引:
    // 在MongoDB Shell或mongoose脚本中执行
    db.RoleListings.getIndexes()
    
  3. 删除包含centralEmail的唯一索引:
    db.RoleListings.dropIndex("centralEmail_1")
    
  4. 重新测试API,重复POST请求即可正常执行。

额外提示:如果Schema有过多次迭代修改,建议定期核对集合的实际索引结构与Schema定义,避免遗留的索引或字段引发异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:01:23