I want to ask your thoughts about best practice to sort objects on expressjs + mongodb(mongoose) web apps.
Let say my Product model has four attributes:
var ProductSchema = new mongoose.Schema({
name: String, // "Summer T-shirt"
price: Number, // 100
salefrom: Date, // ISODate("2018-12-25T10:15:25.338Z")
colors: [String] // "red", "blue", "black"
});
On product list page, I want to implement sort functions as below:
I think there are several ways to achieve it. What do you think is best practice?
First I tried this solution.
For Newest sort and Cheapest sort , mongoose.find().sort() is very easy to use with less coding.
However, Color variations sort can not be done by mongoose.sort() (since it can not sort by array.length), so I have to use another method: mongoose.aggregate().
Next I tried this solution.
Firstly getting array of products using mongoose.find(), then sorting products with Array.prototype.sort() function using compare() like:
function compare(a,b) {
if (a.colors.length < b.colors.length)
return -1;
if (a.colors.length > b.colors.length)
return 1;
return 0;
}
I think this solution is so flexible that I can make more complex sort function which I can not do with mongodb(mongoose) built-in method.
However, with this solution I have to write a lot code comparing to Solution A.
Honestly I have not tried this solution, but since javascript is a language for both server side and client side, I think this is the option for sorting.
From a viewpoint of performance, flexibility and maintenability, which solution do you think is best?
Please share me your thoughts.
Since you asked for an opinion.. Just trying to share my experience with such applications. :)
.sort()
and this performs great. There are places when I don't use mongo's .sort()
but I sort the results with Javascript. This has two points - Array.prototype.sort()
or other means can help.
a. You take the data to browser and sort/or do other actions. In simple words, use client side (browsers) resources. This is where
b. You can not take the data to client and need to show only some part of it after some filtering. But the sorting/other ops need full data. If this is the case, you keep sort/other ops inside the NodeJS code and take only result to Client side.
Point a helps you to take advantage of client side resources. I use that, whenever possible.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.