问题描述
我正在客户端Angular 8中构建应用程序,在服务器端使用MongoDB 4/Mongoose 5构建NodeJS 12.
I am building an application in Angular 8 on the client side and NodeJS 12 with MongoDB 4 / Mongoose 5 on the server side.
我有一个 Angular查询生成器模块以JSON格式生成的查询. JSON对象将通过POST请求发送到后端.
I have a query generated by the Angular query builder module in JSON format. The JSON object will be sent to the backend via a POST request.
问题::如何将JSON查询转换为MongoDB运算符以执行数据库查询?
Question: How can the JSON query be converted into MongoDB operators to perform the database query?
这是由查询生成器插件生成的简单查询的示例.请注意嵌套" AND/OR条件的多个级别的要求.
Here's an example of a simple query generated by the Query Builder plugin. Note the requirement for multiple levels of "nested" AND / OR conditions.
{
"condition": "and",
"rules": [
{
"field": "Brief_D_Reactiedatum",
"operator": "!=",
"value": "Eventtoets_Fn"
},
{
"condition": "or",
"rules": [
{
"field": "Alleen_AO",
"operator": "=",
"value": "Parkeerreden"
}
]
}
]
}
推荐答案
您需要构建MongoDB的 $ expr ,类似于您从 Angular查询构建器模块中获取的查询.由于RuleSet可以嵌套,因此您需要递归运行映射功能.下面的代码可能不会涵盖所有可能的情况,但是应该为您提供一个很好的入门入门.
You need to build MongoDB's $expr which is similar to the query that you're getting from Angular query builder module. Since the ruleSets can be nested you need to run your mapping function recursively. Below code probably doesn't cover every possible case but should give you a good introduction to get started with such mapping.
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);
结果表达式可以传递给MongoDB的find
方法
Result expression can passed either to MongoDB's find
method
db.col.find(mongoDbQuery);
或进入 $ match 管道阶段:
db.col.aggregate([{ $match: mongoDbQuery }]);
这篇关于将JSON查询条件转换为MongoDB/Mongoose操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!