【发布时间】: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