mongoosevalidation匹配一个数组与另一个数组的常见string?

我的mongoose模式+validation

var schemaInterest = new schema({ active_elements: { type: [String] }, pending_elements: { type:[String] } }); schemaInterest.methods.matchElements = function matchElements() { this.find({active_elements: this.pending_elements}, function(){ //shows all the matched elements }); }; 

我不知道如何在mongoose中处理error handling。 我想这样如果元素匹配错误将返回,如果没有匹配,那么validation是成功的。 有任何想法吗?

尝试使用this.pending_elements添加其他属性,并使用lodash库的_.isEqual()_.sortBy()方法比较数组:

 var schemaInterest = new schema({ active_elements: { type: [String] }, pending_elements: { type: [String] } }); schemaInterest.path('active_elements').validate(function (v) { return _.isEqual(_.sortBy(v), _.sortBy(this.pending_elements)) }, 'my error type'); 

更新

从OP注释(感谢@JohnnyHK指出),至less有一个匹配的元素,而不是整个数组是必需的,因此您需要_.intersection()方法创build一个包含在所有使用SameValueZero提供的数组进行相等性比较:

 _.intersection(v, this.pending_elements) 

就足够了。 因此你的validation函数看起来像这样:

 schemaInterest.path('active_elements').validate(function (v) { return _.intersection(v, this.pending_elements).length > 0 }, 'my error type');