Skip to content

custom validation on embedded documents #2746

@Malusia

Description

@Malusia

Hi,

I wrote a custom validation on a embedded document e.g.

var sub = new Schema({
 content: String
});

sub.path('content').validate(function (value) {
 // do something
});

var schema  = new  Schema({
 title: String,
 body: String,
 subDoc: [sub]
});

var myModel = new Model('MyModel', schema);

In the validation callback I can access this. If I validate like example no. 1 this will be the document itself. If I validate like example no. 2 this will be the embedded document.

Example 1

var doc = new myModel({
 title: 'hello',
 body: 'world',
 subDoc: [{
  content: 'hey!'
 }]
});

doc.validate(function () {});

Example 2

var doc = new myModel({
 title: 'hello',
 body: 'world',
 subDoc: [{
  content: 'hey!'
 }]
});

doc.subDoc[0].validate(function () {});

I found in lib/document.js in the validate (master, 3.8.x) method executen of the valdators.

process.nextTick(function(){
    var p = self.schema.path(path);
    if (!p) return --total || complete();

    var val = self.getValue(path);
    p.doValidate(val, function (err) {
        if (err) {
            self.invalidate(path, err, undefined, true);
        }
        --total || complete();
    }, self);
});

I forked the repository, modified the code and run the tests.

process.nextTick(function(){
    var p = self.schema.path(path);
    if (!p) return --total || complete();

    var val = self.getValue(path);
    var parts = path.split('.');
    parts.pop();
    p.doValidate(val, function (err) {
        if (err) {
            self.invalidate(
                path
                , err
                , undefined
                , true // embedded docs
            );
        }
        --total || complete();
    }, parts.length ? self.getValue(parts.join('.')) : self);
});
}

Now this in the validation callback is everytime the embedded document, but I don't know if the current behavior is intended. I can make a pull request, but I want to ask before.

(Sorry for my bad english 😄)

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussionIf you have any thoughts or comments on this issue, please share them!

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions