So I've been working on a project and I finished most of it, but then this error popped up, saying there is something that is undefined, here is the error:
E11000 duplicate key error index: build-a-voting-app.polls.$votedIp_1 dup key: { : undefined }
Here is my code for my create new mongo schema file (polls.model.js)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const pollSchema = new Schema({
title: { type: String, unique: true, required: true },
choices: [
{
title: { type: String, required: true },
count: { type: Number, default: 0 }
}
],
votedIp: [{ type: String, unique: true }],
createdAt: {type:Date, default:Date.now()},
createdBy: String
});
const Poll = mongoose.model('polls', pollSchema);
module.exports = Poll;
Here is the function where I add the inputs
function submitVote(field, res, ip) {
Poll.findOneAndUpdate(
{ choices: { $elemMatch: { title: field } } },
{ $inc: { 'choices.$.count': 1 }, $addToSet: { 'votedIp': ip } },
{ new: true },
function (err, poll) {
if (err) throw err;
res.json({ updated: poll });
}
);
}
Here is how I first created it
var newPoll = new Poll({
title: req.body.title,
choices: choicesArr,
createdBy: req.session.user.username || req.session.user
}).save(function (err, poll) {
if (err) throw err
res.redirect('/mypolls')
});
If you want to see the full code please go to https://github.com/ElisaLuo/Freecodecamp-Build-A-Voting-App
I'm using the ip addresses for checking if the user has voted or not (I'm building a voting app), but right now, I cannot even create a new schema / poll. Does anyone know why the error happens and how I can solve it?

$addToSetjust like you are doing in order to enforce "uniqueness within the array". A "unique index" means across ALL documents. Therefore it is not possible to share a value within that array in any other document. This also includesundefinedandnullvalues. Which is what happens when you create an "empty" array. Remove the index from your database and schema and simply use$addToSetto enforce the logic in your application instead. - Neil Lunn$addToSetor with$pushchecking for the lack of presence of the value in the array before update. - Neil Lunn$push, as in.findOneAndUpdate({ "choices.title": field, "votedIp": { "$ne": ip } },{ "$inc": { "choices.$.count": 1 }, "$push": { "votedIp": ip } },{ "new": true },(err,poll) => { .... The reason being that without that$necheck you$incthe vote count even when the "votedIp" entry already exists. So your logic allows the same "votedIp" value to vote more than once, where you seem to intend that this not be allowed to happen. - Neil Lunn