Skip to content

Instantly share code, notes, and snippets.

@bnoguchi
Created May 3, 2011 09:19
Star You must be signed in to star a gist
Save bnoguchi/953059 to your computer and use it in GitHub Desktop.
How to access enumValues in mongoose from a Model or Document
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);
@iamromec
Copy link

To find enums of all enum properties:

const schema = Temp.schema;
const enums = Object.keys(schema.obj)
        .filter(k => schema.obj[k].hasOwnProperty('enum'))
        .map(k => {
          let o = {};
          o[k] = schema.obj[k].enum;
          return o;
        })
        .reduce((r, v) => Object.assign(r, v), {});

@utsukushiihime
Copy link

Just what I needed. Thank you!

@FrankDev-327
Copy link

FrankDev-327 commented May 25, 2021

for me it worked like this:

//model typeContacts.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const arrayTypeContacts = [
{ type: 'phone', name: 'principal', icon: 'phone' },
{ type: 'email', name: 'principal', icon: 'envelope' },
{ type: 'whatsapp', name: 'principal', icon: 'whatsapp' },
];
const TypeConctactSchema = Schema({
contactType: {
type: String,
enum: arrayTypeContacts,
default: arrayTypeContacts
}
});

const TypeContacts = mongoose.model('typecontacts', TypeConctactSchema);
module.exports = TypeContacts;

//controller
const data = await TypeContactModel.schema.path('contactType').options.enum;

@toryrory
Copy link

thank you a lot!!

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