See here for some decent answers on sorting and
here is some good official docs on mongoose async/await
You should use .exec()
with await for better stack traces, the sort can take these values: asc
, desc
, ascending
, descending
, 1
, and -1
.
try {
let properties = await Property.find(query).sort({"minimumPrice": -1}).exec()
} catch (err) {
console.log(err)
}
This is all assuming your query
is correct and is retrieving documents to be sorted.
UPDATE
I went through your whole situation and created a test using what you provided.
const mongoose = require("mongoose");
var Schema = mongoose.Schema;
var propertySchema = new Schema({
name: String,
minimumPrice: Number
});
var Property = mongoose.model('Property', propertySchema);
//Testing
(async function() {
try {
//connect to mongo
await mongoose.connect('mongodb://localhost:27017/testing', { useNewUrlParser: true, useUnifiedTopology: true });
//First, delete all properties
await Property.deleteMany({}).exec();
let properties = [];
//Insert 5 properties
for (var i = 1; i < 6; i++) {
properties.push({ name: "property" + i, minimumPrice: Math.round(Math.random() * 10000) });
}
//Insert all our random properties
await Property.create(properties);
console.log(properties);
//Now, retrieve all our properties
let sortedProperties = await Property.find({}).sort({ minimumPrice: -1 }).exec();
console.log("sorted", sortedProperties);
} catch (err) {
console.log(err);
}
})();
Database Input:
[
{ name: 'property1', minimumPrice: 3846 },
{ name: 'property2', minimumPrice: 7910 },
{ name: 'property3', minimumPrice: 7234 },
{ name: 'property4', minimumPrice: 4444 },
{ name: 'property5', minimumPrice: 6366 }
]
Sorted Output:
[
{
name: 'property2',
minimumPrice: 7910
},
{
name: 'property3',
minimumPrice: 7234
},
{
name: 'property5',
minimumPrice: 6366
},
{
name: 'property4',
minimumPrice: 4444,
},
{
name: 'property1',
minimumPrice: 3846
}
]
You can see the properties come back sorted. Which leads me to assume, somewhere you've inserted your minimumPrice
as a string.