1

This is my student schema:

var studentSchema = new mongoose.Schema({
   name: String,
   id: Number,
   studmobil: Number,
   email: String,
   address: String,
   isadult: Boolean,
   isparent: Boolean,
   date_of_join: {
      type: Date,
      default: Date.now
      },
   date_of_birth: Date,
   father_name: String,
   mother_name: String,
   parentmob: Number,
   parentemail: String,
   rank:{
            type: mongoose.Schema.Types.ObjectId,
            ref: "Rank"
        },
   graduated: {
      type: Boolean,
      default: false
   },
   payments: [
      {
         payment_type: String,
         amount: Number,
         payment_date: Date
      }
      ]
});

I am trying to sort my payments array in descending order according to date (latest first). This is the code I tried to use:

Student.findById(req.params.id).sort({"payments.payment_date": -1}).populate("rank").exec(function(err, foundstud) {
            console.log(foundstud)
     });

And this is the output I am getting:

payments: 
   [ { _id: 5b7c24f2b3baa30ba965e55b,
       payment_type: 'Tests',
       amount: 600,
       payment_date: 2018-08-08T00:00:00.000Z },
     { _id: 5b7c2502b3baa30ba965e55c,
       payment_type: 'Membership',
       amount: 1000,
       payment_date: 2018-08-21T00:00:00.000Z } ],

The array is still in the order it was inserted in. What am I missing?

abhirham
  • 151
  • 2
  • 12

0 Answers0