pasoc30
pasoc30

Reputation: 141

Sorting in mongoose

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)
  }

Upvotes: 2

Views: 5612

Answers (2)

alonewolf
alonewolf

Reputation: 16

.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 });
}

Upvotes: 0

matt
matt

Reputation: 1753

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.

Upvotes: 8

Related Questions