Skip to content

Commit

Permalink
fix(#63): sorting with strings and arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
Akalanka47000 authored Jul 23, 2024
1 parent d65250f commit 4a25bdb
Show file tree
Hide file tree
Showing 6 changed files with 125 additions and 10 deletions.
19 changes: 12 additions & 7 deletions lib/mongoose-aggregate-paginate.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
* @returns {Promise}
*/

const { parseSort } = require("./util");

const defaultOptions = {
customLabels: {
totalDocs: "totalDocs",
Expand Down Expand Up @@ -86,6 +88,7 @@ function aggregatePaginate(query, options, callback) {
}

const sort = options.sort;

const allowDiskUse = options.allowDiskUse || false;
const isPaginationEnabled = options.pagination === false ? false : true;

Expand All @@ -98,11 +101,13 @@ function aggregatePaginate(query, options, callback) {
}

if (sort) {
pipeline.push({ $sort: sort });
pipeline.push({ $sort: parseSort(sort) });
}

function constructPipelines() {
let cleanedPipeline = pipeline.filter((stage) => stage !== PREPAGINATION_PLACEHOLDER);
let cleanedPipeline = pipeline.filter(
(stage) => stage !== PREPAGINATION_PLACEHOLDER
);

const countPipeline = [...cleanedPipeline, { $count: "count" }];

Expand All @@ -122,7 +127,6 @@ function aggregatePaginate(query, options, callback) {
return [cleanedPipeline, countPipeline];
}


let promise;
if (options.useFacet && !options.countQuery) {
let [pipeline, countPipeline] = constructPipelines();
Expand All @@ -135,14 +139,15 @@ function aggregatePaginate(query, options, callback) {
promise = q
.facet({
docs: pipeline,
count: countPipeline
count: countPipeline,
})
.then(([{ docs, count }]) => [docs, count]);
} else {

const [pipeline] = constructPipelines();

const countQuery = options.countQuery ? options.countQuery : this.aggregate(pipeline);
const countQuery = options.countQuery
? options.countQuery
: this.aggregate(pipeline);

if (allowDiskUse) {
countQuery.allowDiskUse(true);
Expand Down Expand Up @@ -236,4 +241,4 @@ function aggregatePaginate(query, options, callback) {

module.exports = aggregatePaginate;

module.exports.PREPAGINATION_PLACEHOLDER = PREPAGINATION_PLACEHOLDER;
module.exports.PREPAGINATION_PLACEHOLDER = PREPAGINATION_PLACEHOLDER;
3 changes: 3 additions & 0 deletions lib/util/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
...require("./sort"),
};
35 changes: 35 additions & 0 deletions lib/util/sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
function convertSortStringToObject(str) {
const sortObject = {};
str.split(" ").forEach((field) => {
if (field.startsWith("-")) {
sortObject[field.substring(1)] = -1;
} else {
sortObject[field] = 1;
}
});
return sortObject;
}

function convertSortArrayToObject(arr) {
const sortObject = {};
arr.forEach(([field, direction]) => {
sortObject[field] = direction === "asc" || direction === 1 ? 1 : -1;
});
return sortObject;
}

function parseSort(sort) {
if (typeof sort === "string") {
return convertSortStringToObject(sort);
}
if (Array.isArray(sort)) {
return convertSortArrayToObject(sort);
}
const sortObject = {};
for (const [field, direction] of Object.entries(sort)) {
sortObject[field] = direction === "asc" || direction === 1 ? 1 : -1;
}
return sortObject;
}

exports.parseSort = parseSort;
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mongoose-aggregate-paginate-v2",
"version": "1.1.1",
"version": "1.1.2",
"description": "A cursor based custom aggregate pagination library for Mongoose with customizable labels.",
"main": "index.js",
"types": "types/index.d.ts",
Expand Down
72 changes: 72 additions & 0 deletions tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,78 @@ describe("mongoose-paginate", function () {
});
});

describe("sorting", function () {
var aggregate = Book.aggregate([
{
$match: {
title: {
$in: [/Book/i],
},
},
},
]);
it("with object ascending", function () {
return Book.aggregatePaginate(aggregate, {
sort: { date: "asc" },
limit: 40,
}).then((result) => {
expect(result.docs).to.have.length(40);
expect(result.docs[0].title).to.equal("Book #1");
expect(result.docs[result.docs.length - 1].title).to.equal("Book #40");
});
});
it("with object descending", function () {
return Book.aggregatePaginate(aggregate, {
sort: { date: -1 },
limit: 50,
}).then((result) => {
expect(result.docs).to.have.length(50);
expect(result.docs[0].title).to.equal("Book #100");
expect(result.docs[result.docs.length - 1].title).to.equal("Book #51");
});
});
it("with string ascending", function () {
return Book.aggregatePaginate(aggregate, {
sort: "date",
limit: 10,
}).then((result) => {
expect(result.docs).to.have.length(10);
expect(result.docs[0].title).to.equal("Book #1");
expect(result.docs[result.docs.length - 1].title).to.equal("Book #10");
});
});
it("with string descending", function () {
return Book.aggregatePaginate(aggregate, {
sort: "-date",
limit: 10,
}).then((result) => {
expect(result.docs).to.have.length(10);
expect(result.docs[0].title).to.equal("Book #100");
expect(result.docs[result.docs.length - 1].title).to.equal("Book #91");
});
});
it("with array ascending", function () {
return Book.aggregatePaginate(aggregate, {
sort: [["date", "asc"]],
limit: 10,
}).then((result) => {
expect(result.docs).to.have.length(10);
expect(result.docs[0].title).to.equal("Book #1");
expect(result.docs[result.docs.length - 1].title).to.equal("Book #10");
});
});
it("with array descending", function () {
return Book.aggregatePaginate(aggregate, {
sort: [["date", "desc"]],
limit: 10,
}).then((result) => {
expect(result.docs).to.have.length(10);
expect(result.docs[0].title).to.equal("Book #100");
expect(result.docs[result.docs.length - 1].title).to.equal("Book #91");
});
});
});

after(async function () {
await mongoose.connection.db.dropDatabase();
});
Expand Down

0 comments on commit 4a25bdb

Please sign in to comment.