node.js - 是否可以在 Mongoose 中创建多选枚举

标签 node.js mongodb mongoose

我有一个带有枚举字段的模型,目前文档可以具有枚举中的任何单个值。我希望允许文档具有值数组,但 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/

相关文章:

node.js - 如何在保存之前检查该数据是否已存在于数据库中

node.js - 如何更改 Firebase 中的正文解析器限制?

javascript - 使用 Selenium WebDriverJs 关闭警报

javascript - Jade 脚本中未定义 NodeJS 和 Jade/Pug 变量?

java - mongodb java聚合操作

javascript - 如何将我的 meteor 应用程序连接到外部 MongoDB?

mongodb - EmbeddedDocumentSerializer 为每个 ReferenceField 运行查询

node.js - Mongoose - 查找包含子文档引用的文档

javascript - 无法访问 express js router.delete 中的参数

node.js - 与 Mongoose 相比,MongoDB 原生 Node.js 驱动程序的性能很糟糕,我做错了什么?