SeungJun
SeungJun

Reputation: 91

In mongoose, is there a difference between .sort().skip() and .skip().sort()?

As you can see the title, there is difference of .sort().skip() and .skip().sort()?

Does mongoose handle this?

Upvotes: 1

Views: 141

Answers (1)

mickl
mickl

Reputation: 49945

No, there's no difference. .sort() gets always applied before .skip() which makes sense since you want to get results in deterministic order to be able to skip some of them in a predictable manner.

Below queries will return different results since .skip() and .sort() will get reordered for query and kept in specified order for .aggregate():

let results = await Test.aggregate([{ $skip: 2 }, { $sort: { a: 1 } }]);

let results2 = await Test.find().skip(2).sort({ a: 1 });

Internally second syntax simply builds an object of .find() options where there order of keys doesn't matter:

Mongoose: tests.find({}, { skip: 2, sort: { a: 1 }, projection: {} })

or

Mongoose: tests.find({}, { sort: { a: 1 }, skip: 2, projection: {} })

You can add mongoose.set('debug', true); to track that.

Upvotes: 2

Related Questions