是否可以在猫鼬中创建多选枚举

Nat*_*dly 4 mongoose mongodb node.js

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

基本上我想要一个HTML <select multiple>元素而不是一个<select>

Bri*_*len 9

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

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

//... more code to register the model with mongoose
Run Code Online (Sandbox Code Playgroud)

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

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