猫鼬动态枚举值

Vis*_*hnu 4 enums mongoose node.js mongoose-schema

我的猫鼬架构如下。

'use strict';

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

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

mongoose.model('User', UserSchema);
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

//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');
}},
Run Code Online (Sandbox Code Playgroud)

这是我的“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 });
}
Run Code Online (Sandbox Code Playgroud)

完全有效,我正在使用它。