0
votes

I'm trying to make a required field on a nested schema with mongoose 4.4.6 but I never get a validation error.. Here is my minimal non working code:
models/Test.js:

var mongoose = require('mongoose');

var TestChildSchema = mongoose.Schema({
    _id: false,
    testRequiredField: {type: String, required: true} 
});

var TestParentSchema = mongoose.Schema({
    testField: TestChildSchema
});

module.exports = mongoose.model('Test', TestParentSchema);

And I use it like this:
page.js

var mongoose = require( 'mongoose' );
var Test = mongoose.model('Test');

exports.index = function (req, res) {
  var test = new Test();
  test.save(function (err, test) {
    var strOutput; 
     res.writeHead(200, { 
       'Content-Type': 'text/plain'
     }); 
     if (err) { 
       console.log(err); 
       strOutput = 'Oh dear, we\'ve got an error'; 
     } else { 
       console.log('test created: ' + test); 
       strOutput = 'Success'; 
     } 
     res.write(strOutput); 
     res.end(); 
  });

and my app.js:

var http = require('http');  
var mongoose = require('mongoose'); 
var dbURI = 'mongodb://localhost:27017/ConnectionTest'; 
mongoose.connect(dbURI); 
require('./models/Test');
var pages = require('./pages');

http.createServer(function (req, res) {  
  pages.index(req, res);
}).listen(8888, '127.0.0.1');

Why this code doesn't generate a validation error on the nested required field ? Is there another way to generate the validation error ? Am I missing something ?

1

1 Answers

0
votes

Because testRequiredField is undefined after var test = new Test();