Ethan Wu Ethan Wu -4 years ago 126
Node.js Question

Moongoose sort by parseFloat(String)

I want sort my query result by the

Float value
. But the value stored in mongodb is type
String
,Can I parse the
String
to
Float
and sort it dynamically? Just like complex sort.

The following are parts of my schema and sort code:

Schema:

var ScenicSpotSchema = new Schema({
...
detail_info: {
...
overall_rating: String,
...
},
});


Sort function:

ScenicSpot.find({'name': new RegExp(req.query.keyword)}, )
.sort('-detail_info.overall_rating')
.skip(pageSize * pageNumber)
.limit(pageSize)
.exec(function (err, scenicSpots) {
if (err) {
callback(err);
} else {
callback(null, scenicSpots);
}
});


Any kind of help and advice is appreciated. :)

Answer Source

.sort mongoose do not support converting data type. see: http://mongoosejs.com/docs/api.html#query_Query-sort

It only accept column names and order.

There are two path to acheive your goal:

  1. use mapreduce in mongo, first convert type, and the sort
  2. retrieve all data from database, and sort it in your node.js program.

But both are terrible and ugly

if you wanna sort a String column but parse it as Float. This action would scan all data in that collection, and can not use index. It's very very slow action.

So I think the fastest and correct operation is convert the String column to Float in your mongodb database. And then you can use normal .sort('-detail_info.overall_rating') to get things done.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download