要将消息发布到MongoDB,我需要发送带有必填text
字段的架构。但是,即使media
字段也存在(作为可选字段),您也可以发送没有text
字段的请求。我该怎么办?这是代码:
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var Message = new Schema({
text: {type: String, required: true},
media: {type: Object, required: false}
})
答案 0 :(得分:2)
您可以使用提到的here
进行功能验证来尝试此操作var mongoose = require('mongoose')
var Schema = mongoose.Schema
var Message = new Schema({
text: {
type: String,
required: function() {
return !this.media;
}
},
media: {
type: Object,
required: function() {
return !this.text;
}
})