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

I have a circuit like this:

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

And I have to check the values barbased on the values foo, 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 application, 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? What is the correct way to validate this object ??? I was looking for her, but I could not find anything! Even updated my mongoose version to~3.5.5

+5
source share
1 answer

Mongoose does not consider 'bar' itself path, but rather just prefixfor 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;
});

schema.pre(), ( Sub Docs):

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();
});
+6

All Articles