SCENARIO:
At present, I am storing an array of objects within the User model to track all the votes cast by the user.
Here is a glimpse of the model structure:
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
password: {type: String, required: true},
email: {type: String, required: true, unique: true},
polls: [{type: Schema.Types.ObjectId, ref: 'Poll'}],
votes: [{
poll: {type: Schema.Types.ObjectId, ref: 'Poll'},
choice: {type: Number}
}]
});
Whenever a user casts a vote, the following method in the service gets triggered:
voteOn(poll: Poll, userID: string, choice: number) {
UserModel.findById(userID, function (err, user) {
user.votes.push({poll, choice });
const body = JSON.stringify(user);
const headers = new Headers({'Content-Type': 'application/json'});
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.patch('https://voting-app-10.herokuapp.com/user'+token, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => {
this.errorService.handleError(error);
return Observable.throw(error);
})
.subscribe();
});
}
This method essentially records the poll and choice selected by the user in the votes array.
However, my issue lies here:
ISSUE:
Upon loading the polls, I aim to display the ones where the user has already voted with their selections pre-selected, while also preventing them from voting again.
How can I achieve this functionality?
Below is the method from the service that fetches the polls:
getPolls() {
return this.http.get('https://voting-app-10.herokuapp.com/poll')
.map((response: Response) => {
const polls = response.json().obj;
let transformedPolls: Poll[] = [];
polls.reverse();
for (let poll of polls) {
transformedPolls.push(new Poll(
poll.title,
poll.choice1,
poll.choice2,
poll.counter1,
poll.counter2,
poll.user.firstName,
poll._id,
poll.user._id,
)
);
}
this.polls = transformedPolls;
return transformedPolls;
})
.catch((error: Response) => {
this.errorService.handleError(error);
return Observable.throw(error);
});
}
And here is the corresponding HTML snippet for a poll component:
<article class="panel panel-default">
<div class="panel-body">
{{ poll.title }}
<br>
<br>
<form #form="ngForm">
{{ poll.counter1 }} votes <input type="radio" id="{{ poll.choice1 }}" name="my_radio" value="{{ poll.choice1 }}" (click)="onChoice1(form)"> {{ poll.choice1 }}
<br>
{{ poll.counter2 }} votes <input type="radio" id="{{ poll.choice2 }}" name="my_radio" value="{{ poll.choice2 }}" (click)="onChoice2(form)"> {{ poll.choice2 }}
</form>
</div>
<footer class="panel-footer">
<div class="author">
{{ poll.username }}
</div>
<div class="config" *ngIf="belongsToUser()">
<a (click)="onEdit()">Edit</a>
<a (click)="onDelete()">Delete</a>
</div>
</footer>
</article>