Reputation: 193
My mongoose Schema + 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
});
};
I don't know how to work with error handling in mongoose yet. I want it so that if the elements match an error will be return if there is no match then the validation is successful. Any ideas?
Upvotes: 1
Views: 626
Reputation: 103335
Try adding the other property in your validation by using this.pending_elements
and comparing the arrays using the lodash library's _.isEqual()
and _.sortBy()
methods:
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');
-- UPDATE --
From the OP comments (thanks to @JohnnyHK for pointing that out), at least one matching element, not the whole array is required thus you would need the _.intersection()
method which creates an array of unique values that are included in all of the provided arrays using SameValueZero
for equality comparisons:
_.intersection(v, this.pending_elements)
would suffice. Thus your validation function would look like this:
schemaInterest.path('active_elements').validate(function (v) {
return _.intersection(v, this.pending_elements).length > 0
}, 'my error type');
Upvotes: 2