DeLac
DeLac

Reputation: 1122

validate subDocuments in a dictionary in Mongoose

I have a userTasteSchema, with a dictionary field favorites composed by favoriteSchema objects. When I save or update a userTaste, I want to validate that the elements of the dictionary are valid favorite objects. Is it possible? thank you

   var userTasteSchema  = new Schema(
        {  
          favorites     : {type: { /* dictionary of favorites */ }, default:{} }
         });

   var favoriteSchema = new Schema(
      {
       name : {type:{String}}
       });

Upvotes: 1

Views: 344

Answers (1)

Yerko Palma
Yerko Palma

Reputation: 12329

You have to change your model declaration. According to the docs your code should look like:

var userTasteSchema  = new Schema(
    {  
      favorites     : [ favoriteSchema ]
     });

var favoriteSchema = new Schema(
  {
   name : {type:String}
   });

And that's pretty much it. When you save your parent document, UserTaste, your children validations are run as well. Here is the reference

Validation is asynchronously recursive; when you call Model#save, sub-document validation is executed as well. If an error occurs, your Model#save callback receives it

Upvotes: 1

Related Questions