Search code examples
mongodbschemamongoose-schema

best mongodb schema


I have a mongodb schema. I wonder if there is a better approach for this schema.

question: {
    type: String,
    required: true,
  },
  image1: {
    type: String,
    required: true,
  },
  image2: {
    type: String,
    required: true,
  },
  imageOneVotes: {
    type: Number,
    default: 0,
  },
  imageTwoVotes: {
    type: Number,
    default: 0,
  },
  votes: {
    type: Number,
    default: 0,
  }

I need a better schema for this. When I click on the image1 I expect the imageOneVotes to increase. I think it is a bit strange to implement that feature if I go with this schema.


Solution

  • You can either have images as an array of objects, or if you are sure there will only ever be two images then just make each image an object with a "votes" field inside it.

    question: {
      type: String,
      required: true
    },
    images: [{
      url: {type: String, required: true},
      votes: {type: Number, required: true, default: 0}  
    }],
    votes: {type: Number, required: true, default: 0}
    

    OR

    question: {
      type: String,
      required: true
    },
    imageOne: {
      url: {type: String, required: true},
      votes: {type: Number, required: true, default: 0},
    },
    imageTwo: {
      url: {type: String, required: true},
      votes: {type: Number, required: true, default: 0},
    },
    votes: {type: Number, required: true, default: 0}