是否可以在猫鼬中创建多选枚举 [英] Is it possible to create a multi-select enum in mongoose

查看:36
本文介绍了是否可以在猫鼬中创建多选枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有枚举字段的模型,目前文档可以具有枚举中的任何单个值.我希望允许文档具有一组值,但让 mongoose 强制所有值都是枚举中存在的有效选项 - 这可能吗?

I have a model with an enum field, and currently documents can have any single value from the enum. I want documents to be allowed to have an array of values, but have mongoose enforce that all of the values are valid options that exist in the enum - is that possible?

基本上我想要一个 HTML

Essentially I want the equivalent of a HTML <select multiple> element instead of a <select>

推荐答案

是的,您可以将 enum 应用于定义为字符串数组的路径.每个值都将传递给枚举验证器,并进行检查以确保它们包含在枚举列表中.

Yes, you can apply an enum to a path that's defined as an array of strings. Each value will be passed to the enum validator and will be checked to ensure they are contained within the enum list.

var UserSchema = new Schema({
    //...
    pets: {type: [String], enum: ["Cat", "Dog", "Bird", "Snake"]}
    //...
});

//... more code to register the model with mongoose

假设您的 HTML 表单中有一个名为 pets 的多选,您可以从表单帖子中填充文档,在您的路径中,如下所示:

Assuming you have a multi-select in your HTML form with the name pets, you could populate the document from the form post, within your route, like this:

var User = mongoose.model('User');
var user = new User();

//make sure a value was passed from the form
if (req.body.pets) {
    //If only one value is passed it won't be an array, so you need to create one
    user.pets = Array.isArray(req.body.pets) ? req.body.pets : [req.body.pets]; 
}

这篇关于是否可以在猫鼬中创建多选枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆