Question

I do a find and get a single document back. I also have a set of mongo rules. I need to match the document against this set of rules and if the document matches a rule, append the name of the rule to a rule-name subdocument.

Assume the document is this -

var randomGuy = { name: "Random Guy", age: 45, state: "assam", profession: "coder", ruleNames: [] };

I have that stored in a JavaScript variable. I also have a set of rules, converted to mongodb rules -

var rules = [
       {'rule1': { name: /R*/i, age: { $gt: 40 } }},
       {'rule2': { state: "karnataka" }},
       {'rule3': { age: { $lt: 60 } }},
       {'rule4': { $or: [ { profession: 'coder' }, { profession: 'programmer' } ] }}
    ];

I want to loop over the rules, match the randomGuy object against each and append the rule names to the randomGuy's ruleNames property. So the final randomGuy object looks like this -

var randomGuy = { name: "Random Guy", age: 45, state: "assam", profession: "coder", ruleNames: ['rule1', 'rule3', 'rule4'] };
Was it helpful?

Solution

I think i found the answer in sift.js - https://github.com/crcn/sift.js

All i will need to do is apply the rules as sift filters on the randomGuy object.

var randomGuys = [randomGuy];
var ruleName, ruleString;
rules.forEach(function(rule) {
    ruleName = Object.keys(rule)[0];
    ruleString = rule[ruleName];
    if(sift(ruleString).test(randomGuy)) {
        randomGuys.ruleNames.push(ruleName);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top