Renato Gama
Renato Gama

Reputation: 16599

Why can't I validate an embedded document in mongoose? What is the right way to do this?

I have an schema like this:

var testSchema = new Schema({
        foo: { type: String, required: true, trim: true },
        bar: {
            fooBar: { type: String },
            barFoo: { type: String }
        }
});

And I must validate values of bar based on foo values, something like this:

testSchema.path("bar").validate(function(bar){
    if(this.foo === "someValue")
        //return custom validation logic 1
    else if(this.foo === "anotherString")
        //return custom validation logic 2  
    else
        return false;
});

But when I try to strat my app I get the following error:

/Users/Renato/github/local/prv/domain/models/testModel.js:34
testSchema.path("bar").validate(function(bar){
                       ^
TypeError: Cannot call method 'validate' of undefined

What am I doing wrong here? Whats the correct way to validate this object??? I googled for it but I could not seem to find anything out! Even updated my mongoose version to ~3.5.5

Upvotes: 5

Views: 2304

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123563

Mongoose doesn't appear to consider 'bar' to be a path itself, but rather just a prefix for 2 separate paths -- 'bar.fooBar' and 'bar.barFoo':

testSchema.path("bar.fooBar").validate(function(fooBar){
    if(this.foo === "someValue")
        //return custom validation logic 1
    else
        return false;
});

testSchema.path("bar.barFoo").validate(function(barFoo){
    if(this.foo === "anotherString")
        //return custom validation logic 2
    else
        return false;
});

You may also find schema.pre() to be useful for validating the model collectively (another example can be found in the Sub Docs documentation):

testSchema.pre('save', function (next) {
    if(this.foo === "someValue")
        return next(new Error('Invalid 1'));
    else if(this.foo === "anotherString")
        return next(new Error('Invalid 2'));
    else
        next();
});

Upvotes: 6

Related Questions