首页 > 解决方案 > 猫鼬模式中的对象(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); 

但是我如何用它的键具有上面提到的枚举验证器的对象来编写它?

标签: node.jsmongodbexpressmongoose

解决方案


推荐阅读