Conditional Queries with nodeJS

Hi everybody,

i created a webapp, which works like a normal blog with postings. The posts can be filtered by the user.
One way to filter should be by category. There are three categories. My server gets an associative array with the name of the category as key and a boolean as value. If the value is true, the posts should by filtered by the key. It should be also possible to choose more than one category. So what i need is an OR-operation, with conditional queries. I’m struggeling to get it work… any tipps?

Thank you! :slight_smile:

const posts = await Post.find({    
  $or: [
      // only if req.body.category.general is TRUE
      {category: "general"}, 
      // only if req.body.category.jobs is TRUE
      {category: "jobs"}, 
      // only if req.body.category.events is TRUE
      {category: "events"}
  ]
 });

I got a solution (for sure not the best way):

            var categories = req.body.category;
            var selectedCategory = Object.keys(categories).filter(function(key){
                return categories[key];
            });
            var filter = [];
            for(let i of selectedCategory) {
                    filter.push({category: {$regex: i, $options: "i"}});
            }

            
            try {
                if(filter.length > 0) {
                    const posts = await Post.find({$or: filter});   
                    res.status(200).json(posts);
                } else {
                    const posts = await Post.find();  
                    res.status(200).json(posts);
                } 
            } catch (err) {
                res.status(404).json({message: err.message});
            }

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.