diff options
-rw-r--r-- | models/votes/vote.model.ts | 2 | ||||
-rw-r--r-- | models/votes/vote.schema.ts | 9 | ||||
-rw-r--r-- | populateDb.ts | 12 |
3 files changed, 12 insertions, 11 deletions
diff --git a/models/votes/vote.model.ts b/models/votes/vote.model.ts index 1dbb146..df2307e 100644 --- a/models/votes/vote.model.ts +++ b/models/votes/vote.model.ts @@ -1,5 +1,7 @@ import { Model, model } from 'mongoose'; import { VoteSchema, voteSchema } from './vote.schema'; +voteSchema.index({ pollId: 1, userId: 1 }, { unique: true }); // Unique together + export default model<VoteSchema, Model<VoteSchema>>('Vote', voteSchema); diff --git a/models/votes/vote.schema.ts b/models/votes/vote.schema.ts index 709e8bf..63ba212 100644 --- a/models/votes/vote.schema.ts +++ b/models/votes/vote.schema.ts @@ -8,15 +8,18 @@ export interface VoteSchema extends Document, Omit<Vote, '_id'> { export const voteSchema = new Schema({ userId: { type: Types.ObjectId, - ref: 'user' + ref: 'user', + required: true }, pollId: { type: Types.ObjectId, - ref: 'poll' + ref: 'poll', + required: true }, which: { type: String, - enum: ['left', 'right'] + enum: ['left', 'right'], + required: true } }, { timestamps: true }); diff --git a/populateDb.ts b/populateDb.ts index 719b7e7..757280a 100644 --- a/populateDb.ts +++ b/populateDb.ts @@ -8,7 +8,6 @@ import app from './app'; mongoose.connect('mongodb://localhost:27017/which', { useNewUrlParser: true }); const POLLS_AMOUNT = 20; -const VOTES_AMOUNT = 160; const imageUrls: string[] = [ // eslint-disable max-len @@ -59,10 +58,9 @@ const createUser = (username: string): Promise<User> => { const createVote = (userId: string, pollId: string): Promise<Vote> => { return app.service('votes').create({ - userId, pollId, which: _.sample(choices) - }); + }, { user: { _id: userId } }); } @@ -72,13 +70,11 @@ const populate = async () => { const polls = await bluebird.mapSeries(new Array(POLLS_AMOUNT), async () => { const user = _.sample(users); return createPoll(user?._id || ''); - }); - const votes = await bluebird.mapSeries(new Array(VOTES_AMOUNT), async () => { - const user = _.sample(users); - const poll = _.sample(polls); - return createVote(user?._id || '', poll?._id || ''); + const votes = await bluebird.map(users, user => { + const pollsToVote = _.sampleSize(polls, _.random(0, POLLS_AMOUNT)); + return bluebird.map(pollsToVote, poll => createVote(user?._id || '', poll?._id || '')); }); }; |