首页 > 解决方案 > 对象作为属性 mongoose mongodb

问题描述

我需要一个猫鼬模型中的属性,如下所示:

customRanks应该有不同的键和每个键的不同值

const config = new Schema({
  id: { type: String, required: true, unique: true },
 //...other property 
  customRanks: Object,
});

标签: node.jsmongodbmongoose

解决方案


custome rank schema如果您想以特定格式保存customRanks字段的数据,您可以定义并使用它作为对象

const customRanksSchema = new Schema({
  key1: { type: Number, default: 0 },
  key2: { type: Number, default: 0 },
  key3: { type: String, default: '' }
})

如果您想要静态架构并为您的客户排名对象提供特定字段

// if you want to save customeRanks as array of object
customRanks: [{ type: customRanksSchema }],
// if you want to save custom rank as a object
customRanks: customRanksSchema

如果您正在寻找没有密钥的验证。然后,您可能需要在使用 javascript插入/创建/更新之前验证数据。


推荐阅读