我正在客户端使用 Angular 8 构建一个应用程序,在服务器端使用 NodeJS 12 和 MongoDB 4 / Mongoose 5 构建一个应用程序。
我有一个由以下生成的查询角度查询构建器模块 https://www.npmjs.com/package/angular2-query-builderJSON 格式。 JSON 对象将通过 POST 请求发送到后端。
问题:如何将JSON查询转换为MongoDB运算符来执行数据库查询?
以下是查询生成器插件生成的简单查询的示例。请注意以下要求多层次“嵌套”AND/OR 条件。
{
"condition": "and",
"rules": [
{
"field": "Brief_D_Reactiedatum",
"operator": "!=",
"value": "Eventtoets_Fn"
},
{
"condition": "or",
"rules": [
{
"field": "Alleen_AO",
"operator": "=",
"value": "Parkeerreden"
}
]
}
]
}
你需要构建 MongoDB$expr https://docs.mongodb.com/manual/reference/operator/query/expr/这与您收到的查询类似角度查询构建器模块。由于规则集可以嵌套,因此您需要递归地运行映射函数。下面的代码可能没有涵盖所有可能的情况,但应该为您提供一个很好的介绍,以便您开始使用此类映射。
let q = {
"condition": "and",
"rules": [
{
"field": "Brief_D_Reactiedatum",
"operator": "!=",
"value": "Eventtoets_Fn"
},
{
"condition": "or",
"rules": [
{
"field": "Alleen_AO",
"operator": "=",
"value": "Parkeerreden"
}
]
}
]
};
const conditions = { "and": "$and", "or": "$or" };
const operators = { "=": "$eq", "!=": "$ne", "<": "$lt", "<=": "$lte", ">": "$gt", ">=": "$gte" };
const mapRule = rule => ({
[operators[rule.operator]]: [ "$"+rule.field, rule.value ]
});
const mapRuleSet = ruleSet => {
return {
[conditions[ruleSet.condition]]: ruleSet.rules.map(
rule => rule.operator ? mapRule(rule) : mapRuleSet(rule)
)
}
};
let mongoDbQuery = { $expr: mapRuleSet(q) };
console.log(mongoDbQuery);
结果表达式可以传递给 MongoDBfind
method
db.col.find(mongoDbQuery);
or into $match https://docs.mongodb.com/manual/reference/operator/aggregation/match/index.html管道阶段:
db.col.aggregate([{ $match: mongoDbQuery }]);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)