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
});
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 });
}
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.