0

My mongoose version is: "5.13.13",

I created my model called "wordSet" and i my problem is that validation is not working for array.

const schema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Name is required.']
  },
  createdAt: {
    type: Date,
    default: Date.now(),
    select: true,
  },
  category: [ // validation not working here
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Category',
      required: true,
    },
  ],
});

const WordSet = mongoose.model('WordSet', schema);

What i'm doing something wrong?

HazarV17
  • 59
  • 9

1 Answers1

1

I found solution :) I had to set category's type to object with (type, ref) and validate if array contain elements > 0

category: {
    type: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category',
        required: true,
      },
    ],
    validate: [notEmpty, 'Category is required.'],
  },

validation function:

const checkIfEmpty = (array) => {
  if (array.length === 0) {
    return false;
  } else {
    return true;
  }
};
HazarV17
  • 59
  • 9
  • 1
    ah yes, having the array to be filled with something can't be fixed by the default required since that just says the array itself has to be required, ty I learned smth too – Branchverse Dec 14 '21 at 14:38
  • 1
    btw are you using nestjs? becaus ein nestjs you define schemas a little different – Branchverse Dec 14 '21 at 14:40
  • I'm not using nestjs yet. I'm focusing on front-end but i had to make API for my personal project :D – HazarV17 Dec 14 '21 at 14:54