2

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'] };
Mukesh Soni
  • 6,646
  • 3
  • 30
  • 37
  • I think you're going to need to implement a rule engine that understands the rule format you're using. – robertklep Jan 03 '14 at 08:02
  • possible duplicate of [what Javascript library can evaluate MongoDB-like query predicates against an object?](http://stackoverflow.com/questions/15397668/what-javascript-library-can-evaluate-mongodb-like-query-predicates-against-an-ob) – Stennie Jan 05 '14 at 04:41

1 Answers1

2

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);
    }
}
Mukesh Soni
  • 6,646
  • 3
  • 30
  • 37
  • Nice lib, didn't know it existed :) – robertklep Jan 03 '14 at 08:27
  • Got it from this SO answer - http://stackoverflow.com/questions/15397668/what-javascript-library-can-evaluate-mongodb-like-query-predicates-against-an-ob That guy asked the right question ;) – Mukesh Soni Jan 03 '14 at 08:32