Tuesday, 30 May 2017

How to set restrictions on object keys in Schema, Mongoose Nodejs

In my Mongoose Schema I'm trying to simulate a dictionary "offersInCategory" that looks like this:

offersInCategory = [ "Electronics": 2, "Furniture":5 ];

Mongoose doesn't support dictionaries so I'm forced to use object literals instead, like so:

offersInCategory: [{
  category: {
    type: String, 
    enum: ['Furniture', 'Household', 'Electronicts', 'Other']
  },
  val: {
    type: Number, 
    min: 0
  }
}]

My problem with this approach is it feels unintuitive. Furthermore it doesn't prevent my model from creating multiple entries for the same category, as so:

offersInCategory = [ { category: "Furniture", val: 2 }, { category: "Furniture", val: 0} ]

Ideally I'd have my offersInCategory property be structured like this:

offersInCategory : {
  "Furniture" : 0, 
  "Electronics" : 4 
}

But I don't know how to restrict it so that only certain keys can be assigned to the offersInCategory object (kind of like an enum for keys, not values) with no duplicates. I also don't know how to ensure the values for my restricted keys are numbers in a specific range. How can this be accomplished?



via David Tamrazov

No comments:

Post a Comment