本文介绍了猫鼬动态枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的猫鼬架构如下.

'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?

推荐答案

在您的字段上使用验证".例如:

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

这是我的"customEnum"模块

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.

这篇关于猫鼬动态枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 04:23