Creating voting counter

Hi,

I am trying to create a voting system for different website in my Mongo collection, the collection looks liks this:

Websites = new Mongo.Collection(“websites”);
Websites.insert({
title:“Google”,
url:“http://www.google.com”,
description:“Popular search engine.”,
vote: 0,
createdOn:new Date()

I want to access the vote field and put it in a variable, so I can add a counter to it and then put it back, but I can’t seem to target that specific field, I have tried

var counter = Websites.find({vote}) --> this part says vote is not defined in console,
var newvote = counter + 1
Websites.update({_id:website_id},
{$set:{vote:newvote}});

Any advice,

Thank you in advance,

Look into using the Mongo $inc operator:

Websites.update(
  { _id: 'google site id' }, 
  { $inc: { vote: 1 } }
);

well that worked wonderfully, thank you!
Any chance you have an idea why my .find attempt was not working?

Because your find function tries to locate an object called vote which would contain the query. You can’t do it like that.

allright, how should I ave done it, sorry I am just trying to learn, so bear with me

There are few things wrong with it.

First one is that you use find() instead of findOne of find().fetch(), so you can’t use it to retrieve any data, as it’s still a cursor.
Second is that you you didn’t declary any vote object, so you can’t do find({vote}) as it tries to find an object called vote. It’s not the way you look for stuff and wouldn’t work at all even if you had such an object (as then you’d have to use find(vote) instead of find({vote}).
Third is that you try to use find(key) instead of find().key. You should do something like findOne({title:“Google”}).vote, as vote is a property of Websites document, so it’s a property of an object returned by your find.

But even then, you should use $inc like @hwillson suggested.

If you are seriously trying to learn, I suggest to read mongodb documentation on query operators, that’s the best way to master it. It helped me a lot and it’s well written, so I can recommend it.

2 Likes