skip to Main Content

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.

2

Answers


  1. Your mongoDB schema seems good except for the ‘votes’ attribute which seems unclear.

    Is ‘votes’ the total of both votes attributes? I don’t think you need it, you could add both votes everytime you need the total. It will get rid of an unnecessary validation.

    For example -> adding a vote to an image then add one vote to the total is an extra step

    The principal goal of a db is to have a clear view of the data and then be able to easily work with it.

    Login or Signup to reply.
  2. 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}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search