I am making an online Voting System Using MERN Stack and Vote Counter is not working

18 views Asked by At

I'm developing an online voting system using MongoDB and Mongoose, where users can cast their votes for candidates in an election. I have a MongoDB schema for elections with fields for candidates and their vote counts. I'm encountering an issue with updating the vote counter when a user casts a vote. Here's a simplified version of my schema:

{
  "_id": {
    "$oid": "65eafac971d6faXXXXXXX"
  },
  "title": "Testing Election",
  "admin": "[email protected]",
  "startTime": {
    "$date": "2024-03-07T23:49:00.000Z"
  },
  "voter": [
    {
      "email": "[email protected]",
      "voted": false
    },
    {
      "email": "[email protected]",
      "voted": false
    },
    {
      "email": "[email protected]",
      "voted": false
    }
  ],
  "candidate": [
    {
      "email": "[email protected]",
      "votes": 0
    },
    {
      "email": "[email protected]",
      "votes": 0
    },
    {
      "email": "[email protected]",
      "votes": 0
    }
  ],
  "endTime": {
    "$date": "2024-03-08T18:30:00.000Z"
  },
  "__v": 0
}

I have a controller function in my Node.js application to handle vote casting:

const voteCastingController = async (req, res) => {
  const { eid, cid } = req.params;
  const election = await Election.findOne({ _id: eid });
  const user = await User.findOne({ _id: cid });
  await Election.updateOne(
    { "candidate.email": user.email },
    {
      $inc: {
        "candidate.$.votes": 1,
      },
    }
  );
  res.status(200).json({ success: true });
};
module.exports = { voteCastingController };

The problem I'm facing is that the vote counter is not being updated when this function is called. I've tried different syntaxes for the Mongoose update operation, but none seem to work. How can I fix this issue and ensure that the vote counter increments properly every time a vote is cast?

0

There are 0 answers