猫鼬动态枚举值

时间:2017-02-09 04:34:17

标签: node.js mongoose enums mongoose-schema

我有mongoose架构如下。

'use strict';

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

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

mongoose.model('User', UserSchema);

我想从数据库而不是硬编码中动态设置角色枚举值,我该怎么做?

1 个答案:

答案 0 :(得分:2)

在您的字段上使用“验证”。例如:

//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');
}},

这是我的“ customEnum”模块

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

完全可以使用,我正在使用它。