Mongo 在更新文档时出现重复键错误

问题描述 投票:0回答:1

这是我的架构和后端

// Schema definition
const mongoose = require("mongoose");

const ElectionSchema = mongoose.Schema(
    {
        election_name: { type: String },
        candidates: { type: Array },
        votes: { type: Array },
        logo: { type: String },
        voters: { type: Array },
    },
    { collection: "elections" }
);

mongoose.models = {};
module.exports = mongoose.model("Election", ElectionSchema);

// Backend code
import connectDb from "@/middleware/db";
import Election from "@/models/Election";
const jwt = require("jsonwebtoken");

const Vote = async (req, res) => {
    try {
        await connectDb();

        // Find the election by slug
        let v = await Election.findOne({ election_name: req.body.slug });

        // Verify the JWT token
        let u = jwt.verify(req.body.token, "!stackoverflow!");

        // Increment the vote value
        let v_value = v.votes[req.body.i] + 1;

        // Update the election document
        let E = await Election.findOneAndUpdate(
            { election_name: req.body.slug },
            {
                $push: { voters: u.username },
                $set: { [`votes.${req.body.i}`]: v_value },
            },
            { new: true }
        );

        // Send response based on the success of the update
        if (E) {
            res.json({ success: true });
        } else {
            res.json({ success: false });
        }
    } catch (error) {
        console.error("Error in Vote:", error);
        res.status(500).json({ success: false, error: error.message });
    }
};

export default Vote;

它给出的错误是这样的: 投票错误:MongoServerError:findAndModify :: 期间计划执行器错误:由 :: E11000 重复键错误集合引起:voting.elections 索引:voters_1 dup key:{ voters:“qwe”}

一行一行重写了完整的代码仍然无法找出错误在哪里

node.js mongodb mongoose mongoose-schema
1个回答
0
投票

好的,所以我找到了修复方法,以防你们遇到同样的错误。 实际上从模式中删除唯一约束并不会删除该约束。所以你需要自己从 MongoDb atlas 中删除它。 去掉之后。一切都按预期进行。

© www.soinside.com 2019 - 2024. All rights reserved.