【问题标题】:Define an array of objects, each object is a predefined schema定义一个对象数组,每个对象都是一个预定义的模式
【发布时间】:2020-09-03 11:47:14
【问题描述】:

我有两个架构:类别和用户

Category架构定义如下:

title: {
    type: String,
    required: [true, 'Title field is required'],
    unique: true
},
type: {
    type: String,
    required: [true, 'Type field is required'],
}

用户架构

email: {
    type: String,
    required: true
},
isActive: {
    type: Boolean,
    default: true,
    select: false,
},
categories: [{ /* Category schema object */}],

我想要实现的是,当用户注册时,类别数组必须是必需的,并且其中的每个对象都必须匹配并遵循预定义的 category 架构并具有 objectID。

如何用猫鼬做到这一点?

【问题讨论】:

标签: mongodb mongoose


【解决方案1】:

将 Category 架构导入到您定义了 User 架构的文件中,然后只需将类型指定为数组,如下所示:

const Category = require(....);
.
.
.
.
categories: [{
   type: Category,
   ref: "Category"
]

【讨论】:

  • 如果type 是Category,ref 应该是"Category" 而不是"User"
  • 谢谢,它类似于我之前尝试过的逻辑,但我收到了这个错误:无效的架构配置:model is not a valid type within the array categories
  • @MohamedShublaq 你应该输入从new Schema(...)(可能是CategorySchema)返回的内容,而不是从mongoose.model(...)返回的内容
  • @TheeSritabtim 不错!这实际上是一个错误,我将其定义为 categories: [{ type: category, required: true }] 但如果我传递一个空数组,验证根本不会运行,有什么想法吗?
  • @MohamedShublaq 所以你想要一个数组不是空的吗?你试过categores: { type: [category], ref: 'Category', required: true } 吗?
猜你喜欢
  • 1970-01-01
  • 2012-05-19
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
相关资源
最近更新 更多