Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a REST API With Express Completing and Testing the API Test Routes with Postman

mulgey
mulgey
9,899 Points

How does the "sorting" works here?

We have a questionSchema:

const QuestionSchema = new Schema({
    text: String,
    createdAt: {type: Date, default: Date.now},
    answers: [AnswerSchema]
});

And above the Schema, we have our sorting funct:

const sortAnswers = function (a,b) {
    if (a.votes === b.votes) {
        return b.updatedAt - a.updatedAt;
    }
    return b.votes - a.votes;
}

And lastly after these two, we've placed our pre save:

QuestionSchema.pre("save", function(next) {
    this.answers.sort(sortAnswers);
    next();
});

Watching this line of communication, i have difficulty to understand the logic behind the sortAnswers function.

1) In PostMan, or real-world-setting, when we vote up, how does it know to compare A and B, which becomes A and which becomes B?

2) And how the result (negative, 0, positive) affects the sorting? May you provide any documentation link about this?

Kind regards Mustafa

1 Answer