我找了一个并找回一份文件。我也有一套mongo规则。我需要根据这组规则匹配文档,如果文档与规则匹配,请将规则的名称附加到规则名称子文档。
假设文件是这个 -
var randomGuy = { name: "Random Guy", age: 45, state: "assam", profession: "coder", ruleNames: [] };
我将它存储在JavaScript变量中。我也有一套规则,转换为mongodb规则 -
var rules = [
{'rule1': { name: /R*/i, age: { $gt: 40 } }},
{'rule2': { state: "karnataka" }},
{'rule3': { age: { $lt: 60 } }},
{'rule4': { $or: [ { profession: 'coder' }, { profession: 'programmer' } ] }}
];
我想循环遍历规则,将randomGuy对象与每个规则匹配,并将规则名称附加到randomGuy的ruleNames属性。所以最终的randomGuy对象看起来像这样 -
var randomGuy = { name: "Random Guy", age: 45, state: "assam", profession: "coder", ruleNames: ['rule1', 'rule3', 'rule4'] };
答案 0 :(得分:2)
我想我在sift.js中找到了答案 - https://github.com/crcn/sift.js
我需要做的就是将规则作为筛选过滤器应用于randomGuy对象。
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);
}
}