mongoose dynamic enum values

ぃ、小莉子 提交于 2019-12-08 02:12:31

问题


I have mongoose schema as below.

'use strict';

var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var UserSchema = new Schema({
  role: {
    type: String,
    enum: ['user', 'admin']
  }
});

mongoose.model('User', UserSchema);

I want to set role enum values dynamically from database instead of hard coding, How can I do that?


回答1:


Use "validate" on your field. E.G.:

//My field is called "status" inside my schema. So "validate" will check if can pass or not.
status: { type: String, default: 'Abierta', validate: (v) => {
    return customEnum(v, 'Status');
}},

And this is my "customEnum" module

// This is the collection where I store the data. I don't want to use only, status, so
// I made it dynamic, to choose what I want to retrieve.
const SingleValue = require('../models/SingleValue');

module.exports = async (v, type) => {
    return !!await SingleValue.findOne({ typeOf: type, deleted: false, value: v });
}

Totally working, I'm using it.



来源:https://stackoverflow.com/questions/42128321/mongoose-dynamic-enum-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!