猫鼬动态枚举值
mongoose dynamic enum values
我有如下的猫鼬模式。
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var UserSchema = new Schema({
role: {
type: String,
enum: ['user', 'admin']
}
});
mongoose.model('User', UserSchema);
我想从数据库动态设置角色枚举值而不是硬编码,我该怎么做?
在你的领域使用"validate"。例如:
//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 });
}
完全可以,我正在使用它。
我有如下的猫鼬模式。
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var UserSchema = new Schema({
role: {
type: String,
enum: ['user', 'admin']
}
});
mongoose.model('User', UserSchema);
我想从数据库动态设置角色枚举值而不是硬编码,我该怎么做?
在你的领域使用"validate"。例如:
//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 });
}
完全可以,我正在使用它。