简体   繁体   English

将JSON查询条件转换为MongoDB / Mongoose操作

[英]Convert JSON query conditions to MongoDB/Mongoose operations

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 8和NodeJS 12的服务器端使用MongoDB 4 / Mongoose 5构建应用程序。

I have a query generated by the Angular query builder module in JSON format. 我有一个由Angular查询构建器模块以JSON格式生成的查询 The JSON object will be sent to the backend via a POST request. JSON对象将通过POST请求发送到后端。

Question: How can the JSON query be converted into MongoDB operators to perform the database query? 问题:如何将JSON查询转换为MongoDB运算符以执行数据库查询?

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. 请注意“嵌套” AND / OR条件的多个级别的要求。

{
  "condition": "and",
  "rules": [
    {
      "field": "Brief_D_Reactiedatum",
      "operator": "!=",
      "value": "Eventtoets_Fn"
    },
    {
      "condition": "or",
      "rules": [
        {
          "field": "Alleen_AO",
          "operator": "=",
          "value": "Parkeerreden"
        }
      ]
    }
  ]
}

You need to build MongoDB's $expr which is similar to the query that you're getting from Angular query builder module . 您需要构建MongoDB的$ expr ,它类似于从Angular查询构建器模块获取的查询 Since the ruleSets can be nested you need to run your mapping function recursively. 由于RuleSet可以嵌套,因此您需要递归运行映射功能。 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); 

Result expression can passed either to MongoDB's find method 结果表达式可以传递给MongoDB的find方法

db.col.find(mongoDbQuery);

or into $match pipeline stage: 或进入$ match流水线阶段:

db.col.aggregate([{ $match: mongoDbQuery }]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM