Voting
This package adds voting features to a collection.
Vote Schema
An individual vote document is defined according to the following schema:
1 | const schema = { |
Two important properties are:
voteType
: a name such asupvote
ordownvote
. It can also be used for Facebook-style reactions such ashappy
,sad
, or even for 5-star ratings (1stars
,2stars
, etc.).power
: the power of a vote, in other words how many points it should increment the document’s score by.
Defining Vote Types
You can define new vote types using the addVoteType
function:
1 | import { addVoteType } from 'meteor/vulcan:voting'; |
Setting exclusive
to true
means that adding a vote of this type will clear our any votes of any other types (in other words, you can’t have more than one vote at any given time).
Or:
1 | addVoteType('1stars', {power: 1, exclusive: true}); |
Optionally, you can also define power
as a function that takes the current user and document being upvoted as argument:
1 | import Users from 'meteor/vulcan:users'; |
Make Voteable
1 | import { makeVoteable } from 'meteor/vulcan:voting'; |
Calling makeVoteable
on a collection does the following things:
- Add the collection to a
VoteableCollections
array. - Add a set of custom fields to the collection schema (see below).
Custom Fields
currentUserVotes
score
baseScore
Do not forget to add these fields to your fragments for any collection you’re making voteable:
1 | registerFragment(` |
The Vote Mutation
Every collection added to the VoteableCollections
array gets added to a Voteable
union type, which in turn gets returned by the vote
mutation:
1 | vote(documentId: String, voteType: String, collectionName: String, voteId: String) : Voteable |
Calling the mutation a second time with the same vote type will simply cancel the vote (for example, calling vote
with vote type upvote
a second time cancels out the first upvote and removes its power from the document’s score).
Note that the mutation supports passing a voteId
to the server. This is in order to pre-generate an _id
on the client to make sure that the vote object generated as part of the optimistic response and the “real” vote object returned by the server have the same _id
and can be matched.
The withVote Container
The Voting package exports the withVote
container that gives access to the vote
mutation. You can then call the mutation like this (note that this example only implements upvoting, not downvoting):
1 | import { Components, registerComponent, withMessages, withCurrentUser } from 'meteor/vulcan:core'; |
Callbacks
You can make use of the voting package through callbacks as well. For example, here’s how to make every new post be upvoted by its user on creation:
1 | import Posts from 'meteor/example-forum'; |