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

pollSchema.methods.vote = function(userId: string, which: Which): 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);