我有一个带有枚举字段的模型,目前文档可以具有枚举中的任何单个值。我希望允许文档具有值数组,但 Mongoose 强制所有值都是枚举中存在的有效选项 - 这可能吗?
本质上我想要一个 HTML 的等价物 <select multiple>
元素而不是 <select>
最佳答案
是的,您可以将 enum
应用于定义为字符串数组的路径。每个值都将传递给枚举验证器并进行检查以确保它们包含在枚举列表中。
var UserSchema = new Schema({
//...
pets: {type: [String], enum: ["Cat", "Dog", "Bird", "Snake"]}
//...
});
//... more code to register the model with mongoose
假设您在 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];
}
关于node.js - 是否可以在 Mongoose 中创建多选枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27447876/