Dynamically updating allowed values (SimpleSchema/Mongo)

Hi guys, I am trying to set a role for a user based on a predefined list (that is subject to addition or deletion) and I was wondering what the best practice to go about this is.

I am using SimpleSchema (the meteor package, not the npm package) and this is what it looks like currently.

Contact.schema = new SimpleSchema({
  _id: {
    type: String,
    regEx: SimpleSchema.RegEx.Id,
  },
  ...
  role: {
    type: String,
    allowedValues: ['Super', 'Manager', 'Admin'],
  },
})

I basically want the allowedValues to be updated on the client by an admin user. Should this be its’ own collection? A client-side collection (not sure about this, need to research a bit more), or anything else?

Thanks in advance!

You’ll probably want to store whatever change the front end user makes to the list of allowedValues in your server data store, so that it will persist between sessions.

One way to do it would be to do your Roles.find() inside a method, and return the fetched array from there. There may be a better way to use an async function there (I’m not sure if allowedValues is reactive or not), but you could do something like this:

// Server method
Meteor.methods({
  getAllowedRoles () {
    return RolesCollection.find().fetch()
  }
})

// In your Schema definition
Contact.schema = new SimpleSchema({
  ...
  role: {
    type: String,
    allowedValues: function () {
      // if allowedRoles hasn't loaded yet throw an error
      if (!allowedRoles) {
        throw new Error('no allowed roles defined')
      }
      return allowedRoles
    }
  }
})

// enclosed value in the same package as your schema definition
var allowedRoles
Meteor.call('getAllowedRoles', function (err, res) {
  if (err) {
    // do something appropriate with the error
  } else {
    allowedRoles = res
  }
})

Make sure you don’t try to validate your objects until you have your allowedRoles value has loaded from the server.

If you do use a collection directly make sure you set up your pub/sub correctly, and make sure allowedValues is reactive.