Question

I have the following Mongoose schema:

var WeekSchema = new Schema({
    days: [{
        name: String
    }]
});

and I want to get 'name' and do something with it (lets assume a validation). So, I try to validate using the following code:

WeekSchema.path('days.name').validate(function(value){
    return /monday|tuesday|wednesday|thursday|friday|saturday|sunday/i.test(value);
}, 'Invalid day');

but i get the error:

WeekSchema.path('days.name').validate(function(value){
                            ^
TypeError: Cannot call method 'validate' of undefined

in fact if I print the resolved path with

console.log(WeekSchema.path('days.name'));

I have 'undefined'.

The question is, how can I get 'name' by using its path?

Was it helpful?

Solution

I met this issue today so I did a little research by printing out the main path, in your case:

console.log(JSON.stringify(WeekSchema.path('days'), null, 4));
Then I figured out the path to the sub docs to be:

WeekSchema.path('days').schema.path('name');

This is my first answer here, hope it helps :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top