node.js - 猫鼬模式中的对象(node.js)
问题描述
我有一个带有物品和数量的猫鼬捐赠模型。现在我将这些项目保存为一个数组,它的样子:
items: [
{
type: String,
enum: [DONATION_TYPES],
required: true,
},
],
quantity: {
type: Number,
default: 1,
}
DONATION_TYPES 枚举验证器是:
exports.DONATION_TYPES = {
LAPTOP: 'LAPTOP',
HEADPHONES: 'HEADPHONES',
OTHER: 'OTHER',
};
所以数组应该是这样的:
['LAPTOP', 'HEADPHONES', 'OTHER']
我想使用 obj 而不是数组,这样服务器就会得到类似的东西:
{LAPTOP:3, HEADPHONES:5}
我是在前端实现的,但是不知道这种情况下模型怎么写
注意:键必须以某种方式枚举 [DONATION_TYPES]
编辑:这是我在猫鼬文档中找到的最接近的东西:
const userSchema = new Schema({
// `socialMediaHandles` is a map whose values are strings. A map's
// keys are always strings. You specify the type of values using `of`.
socialMediaHandles: {
type: Map,
of: String
}
});
const User = mongoose.model('User', userSchema);
// Map { 'github' => 'vkarpov15', 'twitter' => '@code_barbarian' }
console.log(new User({
socialMediaHandles: {
github: 'vkarpov15',
twitter: '@code_barbarian'
}
}).socialMediaHandles);
但是我如何用它的键具有上面提到的枚举验证器的对象来编写它?
解决方案
推荐阅读
- javascript - JavaScript 基本函数验证运行时错误
- javascript - vue:拼接对当前元素不起作用
- c - (struct Node*)malloc(sizeof(struct Node)); 之间的区别 和 malloc(sizeof(struct Node));
- reactjs - 如何在反应中通过 url 表单 S3 获取图像的 exif 命令?
- javascript - 如何将用户重定向到 url React
- spring-boot - 如何在 Spring Boot 中配置并发 rabbitmq 监听器?
- java - 当我尝试将每条记录写入同一个文件时,只有最后一条记录被写入 json 文件
- python - 类型为类型的对象有什么保证。映射?
- transit-gateway - 使用 AWS 中转网关访问 Internet
- python - 如何对接受参数的python脚本进行单元测试