Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Created September 11, 2023 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jim-clark/70999560fdcf8b6490f11a2fb5725432 to your computer and use it in GitHub Desktop.
Save jim-clark/70999560fdcf8b6490f11a2fb5725432 to your computer and use it in GitHub Desktop.

Accessing Mongoose enum Validator Arrays

If you are using an enum validator in a schema and would like to access and iterate over the enum's strings to, for example, render the <option> tags for a <select> element, you can access the array of strings in your controller function and pass them to your template as follows:

// models/movie.js

const movieSchema = new Schema({
  ...
  mpaaRating: {
    type: String,
    enum: ['G', 'PG', 'PG-13', 'R']
  }
  ...
}, {
  timestamps: true
});

Passing the enum Array of Strings to the EJS Template

Here's how to pass the enum array of strings, e.g., ['G', 'PG', 'PG-13', 'R'], from the controller to the view:

function newMovie(req, res) {
  const validRatings = Movie.schema.path('mpaaRating').enumValues;
  res.render('movies/new', { validRatings });
}

Iterating Over the Array of Strings in the EJS Template

In the view you can iterate over the array of strings with a forEach and render an <option> for each string:

<select name="mpaaRating">
  <% validRatings.forEach(function(rating, idx) { %>
    <option value="<%= rating %>" <%= idx === 0 ? 'selected' : ''%>>
        <%= rating %>
    </option>
  <% }) %>
</select>

Note that whatever is assigned to the value attribute is what will be sent to the server if that option is selected and whatever is rendered between the <option> and </option> tags is what the user will see for that option.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment