Hey again, I’m still stuck on the voting app challenge. This time I want to track which IP address has voted on which question (to stop them voting more than once) but I’m unsure how to specifically check if the question document has the IP address or not.
I’m using the MongoDB node.js driver.
First, I store their IP in the question document in the questions collection:
var questionId = ObjectId(req.body._id);
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
ip = ip.replace("::ffff:", "").replace(/\./g, "");
db.collection('questions')
.findOneAndUpdate({"_id": questionId}, {$set : {[ip] : true} }, (err, result) => {
if (err) return res.send(err)
})
However, I want to verify that the IP does not already exist in the question’s document.``
So I want to check if {’_id’: questionId} has: {[ip]: true} or even ip as a field.
The database entry looks like this (edited for clarity):
{
"_id": {
"$oid": "58caeb3402f11c2d66dc3f41"
},
"question": "Metallica or Megadeth?",
"answer1": "Metallica",
"answer2": "Megadeth",
"answer1_votes": 14,
"answer2_votes": 11,
"127001": true
}
As we can see 127.0.0.1 has voted already, so I would want to stop that user voting again on that question.
I’m doing it with the IP as I want non-registered users to be able to vote.
I’m sure it’s very simple, but I’m lost completely.