How to build a conditional query in Mongoose?

后端 未结 3 1740
生来不讨喜
生来不讨喜 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:50

    You don't need to call Query#where repeatedly, since you can pass all the conditions to Mongoose Model#find as:

    var filteredQuery = {},
      acceptableFields = ['gender', 'race', /* etc */ ];
    
    acceptableFields.forEach(function(field) {
      req.query[field] && filteredQuery[field] = req.query[field];
    });
    
    var query = Character.find(filteredQuery);
    

    You'll also want to sanitize req.query depending on the allowed parameters you have in mind.

提交回复
热议问题