aboutsummaryrefslogtreecommitdiff
path: root/models/polls/poll.model.ts
blob: 11d0cfadb54dff0e6edd75be3dc494b8f80398af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { Model, model } from 'mongoose';
import { PollSchema, pollSchema } from './poll.schema';
import { Types } from 'mongoose';

pollSchema.methods.vote = function(userId: string, which: 'left' | 'right'): PollSchema {
  const participants: Types.ObjectId[] = ['left', 'right'].reduce((acc, option) => {
    const { votes } = this.contents[option];
    return acc.concat(votes);
  }, []);

  if (!participants.some(user => user.equals(userId))) {
    this.contents[which].votes.push(userId);
  }

  return this.save();
}

export default model<PollSchema, Model<PollSchema>>('Poll', pollSchema);