0

I have two schemas: Category, and User

Category schema is defined as follows:

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

User schema

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

What I'm trying to implement is when ever a user registers, the categories array must be required, and each object within it must match and follow the predefined category schema and have an objectID.

How to do that with Mongoose?

1

1 Answer 1

0

Import the Category schema into the file where you have defined the User schema, then simply specify the type as array, like this:

const Category = require(....);
.
.
.
.
categories: [{
   type: Category,
   ref: "Category"
]
Sign up to request clarification or add additional context in comments.

5 Comments

If type is Category, ref should probably be "Category" not "User"
thanks, it similar to the logic I tried before and I was getting this error: Invalid schema configuration: model is not a valid type within the array categories
@MohamedShublaq you should put what's returned from new Schema(...) (probably CategorySchema) not what's returned from mongoose.model(...)
@TheeSritabtim Nice! that was the mistake actually, I defined it as categories: [{ type: category, required: true }] but the validation is not running at all if I'm passing an empty array, any ideas?
@MohamedShublaq so you want an array to be required and not empty? Have you tried categores: { type: [category], ref: 'Category', required: true } ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.