【发布时间】:2017-10-18 13:35:08
【问题描述】:
情况:
目前,我在我的用户中存储了一个对象数组,其中包含他所投的所有选票。
这是模型:
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}
}]
});
当用户选择一个选项时,这个方法会在我的服务内部触发:
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();
});
}
此方法将用户投票的投票和他所做的选择保存在用户的投票数组中。
我的问题如下:
问题:
当投票加载时,我想将用户已经投票的投票显示为预先选择了他所做的选择,并防止他多次投票。
我怎样才能做到这一点?
这是我的服务中获取投票的方法:
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);
});
}
这是用于投票的 component.html:
<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>
【问题讨论】:
标签: mongodb angular typescript mongoose