Automattic / Automattic/mongoose

Validators should work for nested objects

Open
#3,896 1 comment 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

(From https://github.com/Automattic/mongoose/issues/3587#issuecomment-184918722)

Validators on nested objects currently don't work. Using subdocuments works around this for now, but it would be nice if directly using nested objects would work.

For example, using this test case:

``` js
"use strict";

const mongoose = require("mongoose");
mongoose.connect("localhost/test");

const schema = new mongoose.Schema({
a: {
$type: {
a: {
$type: String,
required: true
}
},
required: true
}
}, {
strict: "throw",
typeKey: "$type"
});

const Test = mongoose.model("Test", schema);

// Should throw for missing `a.a` and extra `a.b`
Test.create({a: {b: "test"}}).then(function (record) {
console.log(record.validateSync());
console.log(record);
}).catch(e => console.log(e));
```

throws:

```
TypeError: Undefined type `undefined` at `a.$type.a.required`
Did you try nesting Schemas? You can only nest using refs or arrays.
at Function.Schema.interpretAsType (/tmp/node_modules/mongoose/lib/schema.js:598:11)
```

Contributor guide

Open the contributing guide

Research direction

Reproduce the nested-object example, then inspect lib/schema.js around Schema.interpretAsType and line 598, where the reported error occurs. Confirm that directly nested validators accept the schema definition, enforce missing a.a, and still reject extra a.b under strict mode.

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
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.