Automattic / Automattic/mongoose

custom validation on embedded documents

Open
#2,746 14 comments 0 reactions 0 assignees View on GitHub
discussion
Dominant language
JavaScript
Stars
27.5k
Forks
4k
Avg merge
2d 7h
Merged PRs (30d)
35

Description

Hi,

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

``` javascript
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

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

doc.validate(function () {});
```

Example 2

``` javascript
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](https://github.com/LearnBoost/mongoose/blob/master/lib/document.js#L1024-L1035), [3.8.x](https://github.com/LearnBoost/mongoose/blob/3.8.x/lib/document.js#L969-L986)) method executen of the valdators.

``` javascript
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.

``` javascript
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 :smile:)

Contributor guide

Open the contributing guide

Research direction

Start in lib/document.js at the validate method and compare the callback context in the two embedded-document examples. Review the validation tests the reporter ran, then determine whether callbacks should receive the parent document or embedded document and add regression coverage for the intended behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, mongodb, nodejs
Domain
backend, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.