skip to Main Content

In Nodejs, I want to use the .sort() method for an ascending / descending feature in a mongoose query. It works when entering "title" or "-title" hardcoded, but I want to make it dependent on the user entry, which should be represented by a variable. When using the variable, it won’t recognize my String.

This does NOT work:

const filterForMovie = async(req,res)=>{
    try {
        let {title, publishDate, genre, skip, limit, sort} = req.query;
        const queryObject = {};
        if(title){
            queryObject.title = title;
        }
        if(publishDate){
            queryObject.publishDate = publishDate;
        }
        if(genre){
            queryObject.genre = genre;
        }
        if(sort){
            sort === "Ascending" ? sort = "-title" : sort = "title";
        }
        let data = await Movie.find(queryObject).limit(Number(limit)).sort(sort).skip(Number(skip));
        res.status(200).json(data);
    } catch (error) {
        console.log(error)
    }
}

Changing the variable to the actual String works:

const filterForMovie = async(req,res)=>{
    try {
        let {title, publishDate, genre, skip, limit, sort} = req.query;
        const queryObject = {};
        if(title){
            queryObject.title = title;
        }
        if(publishDate){
            queryObject.publishDate = publishDate;
        }
        if(genre){
            queryObject.genre = genre;
        }
        if(sort){
            sort === "Ascending" ? queryObject.sort = "-title" : queryObject.sort = "title";
        }
        let data = await Movie.find(queryObject).limit(Number(limit)).sort("title").skip(Number(skip));
        res.status(200).json(data);
    } catch (error) {
        console.log(error)
    }
}

Why exactly is the variable not considered as a valid sort criteria. The typeof sort shows String.

2

Answers


  1. Chosen as BEST ANSWER

    For everyone in the future: The solution is case sensitivity. The logic is checking for the "Ascending" value and I provided "ascending" via the request. Adjusting the capitalization fixed it.


  2. I believe the variable sort is undefined in your first example, which is why the string title is not being assigned. In your second example, title is a constant and always is taken as sort parameter. You can try changing your code in this way:

            sort = sort && sort === "Ascending" ? "-title" : "title"
    

    I don’t recommend to mutate variables since it’s a bad a practice I suggest you to define other variables to make your logic as pure as possible. Mutations issues are a nightmare in long term.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search