简体   繁体   中英

mongoose required field nested schema

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 ?

因为在var test = new Test();之后,testRequiredField是未定义的var test = new Test();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM