Search code examples
javascriptnode.jssortingmongoose

.sort() method does not sort when using a variable


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.


Solution

  • 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.