public
Last active

How to access enumValues in mongoose from a Model or Document

  • Download Gist
enum-access.js
JavaScript
1 2 3 4 5 6 7 8 9 10
var mongoose = require('./index')
, TempSchema = new mongoose.Schema({
salutation: {type: String, enum: ['Mr.', 'Mrs.', 'Ms.']}
});
 
var Temp = mongoose.model('Temp', TempSchema);
 
console.log(Temp.schema.path('salutation').enumValues);
var temp = new Temp();
console.log(temp.schema.path('salutation').enumValues);

So neat, but doesn't work for me (mongoose 3.6.20): for the path() function, my enum fields must be prefixed with ".enum", and there is no "enumValues" property on the returned object. This works for me... console.log(Temp.schema.path('salutation.enum').options.type) // We get ['Mr.', 'Mrs.', 'Ms.']

Update: bnoguchi's neater version works if you do Temp.path("salutation").enum('Mr.', 'Mrs.', 'Ms.'); after you've defined the schema (i was using salutation: {enum: ['Mr.', 'Mrs.', 'Ms.']} in the Schema constructor parameter, which doesn't seem to work as well).

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.