mongoose需要字段嵌套模式

时间:2016-03-06 17:02:38

标签: javascript node.js mongodb mongoose

我尝试使用mongoose 4.4.6在嵌套模式上创建必填字段,但我从未收到验证错误。这是我的最小非工作代码:
模型/ 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);

我这样使用它:
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(); 
  });

和我的 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');

为什么此代码不会在嵌套的必填字段上生成验证错误?还有另一种方法来生成验证错误吗?我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

因为在var test = new Test();

之后未定义testRequiredField