gpt4 book ai didi

node.js - Mongoose 动态枚举值

转载 作者:太空宇宙 更新时间:2023-11-03 21:55:34 24 4
gpt4 key购买 nike

我的 Mongoose 架构如下。

'use strict';

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

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

mongoose.model('User', UserSchema);

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

最佳答案

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

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

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

关于node.js - Mongoose 动态枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42128321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com