Skip to content

Instantly share code, notes, and snippets.

@binki
Created August 22, 2017 04:48
Show Gist options
  • Save binki/8d262eda2134756e695ecf5e3253450a to your computer and use it in GitHub Desktop.
Save binki/8d262eda2134756e695ecf5e3253450a to your computer and use it in GitHub Desktop.
impossible to require null or disallow undefined
const assert = require('assert');
const mongoose = require('mongoose');
const ThingSchema = new mongoose.Schema({
// https://stackoverflow.com/a/44336895/429091, doesn’t support
// subdocuments.
undefinedDisallowed: {
type: String,
required: function () {
return this.undefinedDisallowed === undefined;
},
default: null,
},
});
const Thing = mongoose.model('Thing', ThingSchema);
const thing = new Thing();
assert.ifError(thing.validateSync());
thing.undefinedDisallowed = undefined;
assert.ok(thing.validateSync());
const SuperDocumentSchema = new mongoose.Schema({
thing: {
type: ThingSchema,
// https://stackoverflow.com/q/35494875/429091
default: ThingSchema,
},
});
const SuperDocument = mongoose.model('SuperThing', SuperDocumentSchema);
const superDocument = new SuperDocument();
// We have to mark the value dirty to cause validation to happen.
superDocument.thing.undefinedDisallowed = null;
// Throws because superThing.undefinedDisallowed is undefined even
// though superThing.thing.undefinedDisallowed is null.
assert.ifError(superDocument.validateSync());
ohnob@DESKTOP-A4G2C0J MSYS ~/repos/mongoose-validators-hard-to-use
$ node --version
v6.11.1
ohnob@DESKTOP-A4G2C0J MSYS ~/repos/mongoose-validators-hard-to-use
$ node index.js
assert.js:377
assert.ifError = function(err) { if (err) throw err; };
^
ValidationError: SuperThing validation failed: thing.undefinedDisallowed: Path `undefinedDisallowed` is required.
at MongooseError.ValidationError (C:\Users\ohnob\repos\mongoose-validators-hard-to-use\node_modules\mongoose\lib\error\validation.js:28:11)
at model.Document.invalidate (C:\Users\ohnob\repos\mongoose-validators-hard-to-use\node_modules\mongoose\lib\document.js:1611:32)
at C:\Users\ohnob\repos\mongoose-validators-hard-to-use\node_modules\mongoose\lib\document.js:1557:13
at Array.forEach (native)
at model.Document.validateSync (C:\Users\ohnob\repos\mongoose-validators-hard-to-use\node_modules\mongoose\lib\document.js:1539:9)
at Object.<anonymous> (C:\Users\ohnob\repos\mongoose-validators-hard-to-use\index.js:38:30)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:504:3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment