I'm new to node, express and mongodb and I have been looking at documentation and other StackOverflow for a few hours and still haven't managed to figure this out.
I'm using the MongoDB node.js driver.
I am trying to create a voting app where people can only vote once per poll. To do this 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.
via swhizzle
No comments:
Post a Comment