【问题标题】:mongoose required field nested schema猫鼬必填字段嵌套架构
【发布时间】:2016-06-20 04:15:33
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

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

    【讨论】:

    • 好吧,如果我的字段未定义,他是否应该生成验证错误,因为我希望它是必需的?
    猜你喜欢
    • 2021-05-06
    • 2015-06-04
    • 2013-10-07
    • 2019-03-15
    • 2021-08-27
    • 2015-02-09
    • 2018-10-15
    • 2021-11-07
    • 2014-07-28
    相关资源
    最近更新 更多