How to build a conditional query in Mongoose?

后端 未结 3 1738
生来不讨喜
生来不讨喜 2020-12-29 13:46

The following code works with no querystrings or one querystring only. In other words, simply going to /characters returns all

3条回答
  •  情话喂你
    2020-12-29 14:28

    Well,

    I would recommend something like this:

    var query = Character.find()
    if(req.params.length < 0) {
      for(var key in req.params) {
        query.where(req.params[key]).equals(key);
      }
    } else {
      // do something without query params
    }
    

    this is not tested by me but it should work (maybe you need to modify it a bit but you get the idea). This solution is all about not checking what actually is in the params so be sure only good stuff comes in or validate it somewhere in the for loop, but would require some regex or if statements.

    Hope this helps you.

提交回复
热议问题