swhizzle
swhizzle

Reputation: 141

MongoDB/Node- Check if a document within a collection has a specific field

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.

Upvotes: 1

Views: 636

Answers (1)

s7vr
s7vr

Reputation: 75964

You can fix this by moving the ip to a value position.

Something like "ip" : 127001.

You can now easily check for the presence of ip field and/ its value.

The below query will look for ip field in question, if its finds; do nothing, else set ip to the question document.

db.collection('questions').findOneAndUpdate({"_id": questionId, "ip": { $exists: false } }, {$set : {"ip" : 127001} }, (err, result) => {
    if (err) return res.send(err)
})

Upvotes: 1

Related Questions