猫鼬必填字段嵌套架构

mongoose required field nested schema

本文关键字:嵌套 字段      更新时间:2023-09-26

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

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

和我的应用程序.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');

为什么此代码不会在嵌套的必填字段上生成验证错误?有没有其他方法可以生成验证错误?我错过了什么吗?

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