Mongo giving duplicate key error when updating a document

28 views Asked by At

Here's my schema and the backend

// 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;

The error it is giving is this: Error in Vote: MongoServerError: Plan executor error during findAndModify :: caused by :: E11000 duplicate key error collection: voting.elections index: voters_1 dup key: { voters: "qwe" }

Rewrote the full code line by line still couldn't figure out where the error is

1

There are 1 answers

0
Vraj On

Okay So I found the fix in case any of you encountering the same error. Actually removing unique constraint from the schema doesn't remove the constraint. You need to remove it from MongoDb compass( or any way you access the database) yourself. After removing it. It all works as expected.