Poll Answer

Apart from working on the login redirect yesterday, I also worked on the UI for the poll answer page. Today’s work is mainly storing the poll answers to the database.

I previously chose the poll schema such that it embeds poll answers within the poll itself. I thought this might be a convenient way to store data as a single delete request would remove the poll together with its associated answers. However, I ran into a lot of problems trying to get data stored as an embedded document within an existing Poll object.

Eventually, I decided that having a separate collection for poll answers may be a more suitable option.

/lib/models/answer.js —

/**
 * Answer Schema
 */
var AnswerSchema = new Schema({
 owner_id: Schema.Types.ObjectId,
 poll_id: Schema.Types.ObjectId,
 answer: Number,
 updated_at: { type: Date, default: Date.now }
});

/lib/models/poll.js —

/**
 * Poll Schema
 */
var PollSchema = new Schema({
  question: { type: String, required: true, trim: true },
  owner_id: Schema.Types.ObjectId,
  active: { type: Boolean, default: false },
  choices: [ { type: String, required: true, trim: true} ],
  created_at: { type: Date, default: Date.now }
});

PollSchema.path('choices').validate(function (value) {
  return value.length >= 2 && value.length <= 8;
}, 'Number of choices invalid');