Search code examples
node.jsmongodbmongoosemongoose-schema

How to add multiple properties of the same type object in mongoose schemas


How can I add multiple (1,2,3...x) genres for my movies in my moongoose schema?

I have this genre schema that I use in my movie schema:

const genreSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  }
});

Movie schema:

const Joi = require('joi');
const mongoose = require('mongoose');
const {genreSchema} = require('./genre');


const Movie = mongoose.model('Movie', new mongoose.Schema({
  title:  {
    type: String,
    required: true,
    trim: true,
    minlength: 5,
    maxlength: 255,
  },
  genre: {
    type: genreSchema,
    required: true
  },
  numberInStock: {
    type: Number,
    required: true,
    min: 0,
    max:255
}
}));

function validateMovie(movie) {
  const schema = {
    title: Joi.string().min(3).required(),
    genreId: Joi.objectId().required(),
    numberInStock: Joi.number().min(0).required(),
  };

  return Joi.validate(movie, schema);
}

I also want to validate the schema with Joi.


Solution

  • An array of genres? You can define your model this way :

     genre: [{
        type: genreSchema,
        required: true
      }],