Search code examples
mongodbmongoose

Query any/specific using single/multiple values without using if blocks


I've finally managed to get my filter to work properly, however I am using a bunch of if/else statements, can this code be simplified, can the conditions be parts of the actual queries?

category is a string and difficulty is an array, searchTerm is not important

if (category && difficulty) {
        recipes = await Recipe.find({
            ...searchTerm,
            difficulty: { $in: difficulty.split(",") },
        })
            .where("category")
            .equals(category);
    } else if (category) {
        recipes = await Recipe.find({ ...searchTerm })
            .where("category")
            .equals(category);
    } else if (difficulty) {
        recipes = await Recipe.find({
            ...searchTerm,
            difficulty: { $in: difficulty.split(",") },
        });
    } else {
        recipes = await Recipe.find({ ...searchTerm });
    }

Solution

  • You can build the query before providing it to the .find() query as below:

    if (category) {
        searchTerm = {
            ...searchTerm,
            category: category
        }
    }
    
    if (difficulty) {
        searchTerm = {
            ...searchTerm,
            difficulty: { $in: difficulty.split(",") }
        }
    }
    
    recipes = await Recipe.find(searchTerm);
    

    Besedies, you can chain the .where() with multiple (filter) conditions and execute the query when it is ready.

    let query = Recipe.find(searchTerm);
    
    if (category) {
        query = query.where("category")
            .equals(category);
    }
    
    if (difficulty) {
        query = query.where("difficulty")
            .in(difficulty.split(","));
    }
    
    recipes = await query.exec();