2

Alright, this is very wierd but the sort does not work. it does not throw any error but the sort does not work.

try {
    properties = await Property.find({}).sort("-minimumPrice");
 
  } catch (err) {
   console.log(err)
  }

I also tried but it didnt work as well:

try {
    properties = await Property.find({}).sort({minimumPrice: "desc"});
 
  } catch (err) {
   console.log(err)
  }
pasoc30
  • 141
  • 2
  • 7
  • yes. Still no good. The entire sort thing does not work – pasoc30 Jul 31 '20 at 12:17
  • my data: { name: property1 minimumPrice: 4000, } { name: property2 minimumPrice: 8000 } Now expected result should be, property2 should be returned first – pasoc30 Jul 31 '20 at 12:23

2 Answers2

7

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.

matt
  • 1,680
  • 1
  • 13
  • 16
  • still not working. I tried await Property.find({}).sort({ minimumPrice: -1 }).exec(); just to verify that the problem is not from the query parameter i set with the find method – pasoc30 Jul 31 '20 at 12:30
  • What version of mongo and mongoose are you using @pasoc30? – matt Jul 31 '20 at 12:31
  • Is it possible you inserted minimumPrice as a string? `MongoDB can't sort by numbers stored as strings.` – matt Jul 31 '20 at 12:35
  • mongoose 5.9.6. im using atlas for the database. – pasoc30 Jul 31 '20 at 12:35
  • 1
    nahhh i tripled checked it. data type is int32 – pasoc30 Jul 31 '20 at 12:36
  • @pasoc30 Super odd, can't seem to figure out what the issue is. I'll try setting up a test and get back to you. – matt Jul 31 '20 at 12:39
  • Yea its really wierd. i used to apply these before and they were working, dont know what happened right now – pasoc30 Jul 31 '20 at 12:55
  • @pasoc30 Please see my updated answer, ran through and made a test that functions just fine. You must have inserted the minimumPrice as a string somewhere, thats all I can think would be the issue. Maybe try looping over your properties via a script and alter their minimumPrice value – matt Jul 31 '20 at 12:59
  • @pasoc30 Let me know if it works by marking my answer as a solution. If not, I can help do some more digging for you. Just add some more details to your question. Cheers. – matt Jul 31 '20 at 13:19
0

.sort() chaining works for me with await:

const getAllProducts = async (req, res) => {
    const { featured, company, name, sortWith } = req.query;

    const queryObject = {}

    if (featured) {
        queryObject.featured = featured === 'true' ? true : false;
    }
    if (company) {
        queryObject.company = company;
    }
    if (name) {
        queryObject.name = { $regex: name, $options: 'i' };
    }

    // Here I'm sorting with provided query in sotWith or by default sorting latest products using 'createdAt' from mongoDB

    const products = await Product.find(queryObject).sort(sortWith ? sortWith.split(',').join(' ') : 'createdAt');

    res.status(200).json({ products, nbHits: products.length });
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31