如何检查用户已对投票进行投票? [英] How to check that a user has already voted on a poll?

查看:132
本文介绍了如何检查用户已对投票进行投票?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:

当前,我在用户内部存储了一个对象数组,其中包含他所投的所有票.

Currently, I store an array of objects inside my User which contains all the votes he has cast.

这是模型:

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}
    }]
});

当用户选择一个选项时,此方法将在我的服务中触发:

When a user selects an option, this method is triggered inside my service:

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 saves the poll the user has voted and the choice he made inside the votes array of the user.

我的问题如下:

问题:

加载民意调查时,我想显示用户已对其进行投票的民意调查,以使其具有预先选择的选择权,以及阻止其多次投票.

When the polls load, I would like to show the polls on which the user has already voted on as having the choice he made pre-selected as well as preventing him from voting more than once.

我该如何实现?

这是我的服务中获取民意调查的方法:

Here is the method inside my service which gets 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);
            });
    }

这是民意调查的component.html:

And here is the component.html for a poll:

<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>

推荐答案

有很多方法可以做到这一点.

There are a lot of ways you could do this.

在不更改当前数据模型的情况下,您需要做的是将poll.id与user.votes [pollIndex] .id进行比较,如果它们与轮询中的禁用输入相匹配.来自ReactJS的背景,我可以建议如何做到这一点,但IDK带有角度.

Without changing your current data model what you need to do is compare the poll.id to the user.votes[pollIndex].id and if they match disable input on the poll. Coming from a ReactJS background I could advise how to do this but IDK with angular.

如果我要接管这个项目,我可能会制作一个名为Vote或UserPoll的新Mongo模式,例如:

If I were to take over this project, I would probably make a new Mongo schema called Vote or UserPoll like:

{
    user: {type: Schema.Types.ObjectId, ref: 'User'),
    poll: {type: Schema.Types.ObjectId, ref: 'Poll'},
    choice: {type: number}
}

然后,如果用户要进行轮询,请与当前用户一起创建一个新的UserPoll对象并进行轮询.然后,您可以找到当前用户所在的所有UserPoll,然后根据是否可以选择使用数组过滤器.

Then if a user want to take a poll, create a new UserPoll object with the current user and poll. Then you can find all the UserPolls that the current User is in and then use an array filter based on if there is a choice or not.

希望这是有道理的.

这篇关于如何检查用户已对投票进行投票?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆