Mongoose Sorting

672 Views Asked by At

I have a problem with displaying data with sorting. Here is my query,

Activity.find({"user_id": sesUser._id}, {}, {offset: 0, limit : 5, sort:{createdAt:1}}, function (e,a){
    ...
  });

I have data about 252 length, and my latest data is 9 June 2015. If i use this query i only get data from 5 June 2015/ last week data and not get the latest data, but if i not using sorting, the latest data is appear.

I have used this query below but turns out the result is same.

Activity.find({"user_id" : sesUser._id}).sort("createdAt").exec(function(err,a){
    ...
  });

Any help? I'm using Mongoose v3

-- edited -- This is my Activity Schema / Model

var mongoose = require('mongoose');

var Activity = mongoose.Schema({
  sender_id : {type: String, required: true },
  user_id : {type: String, required: true },
  product_id : {type: String, default : "" },
  type : {type: String, required: true },
  createdAt : {type: String, default : new Date()}
});

module.exports = mongoose.model('Activity', Activity);
2

There are 2 best solutions below

3
On BEST ANSWER
`createdAt : {type: Date, default : new Date()}`

Type Date not string man

0
On

It will automatically create the createdAt and updatedAt

var options={
      timestamps: true
 }

var Activity = mongoose.Schema({
  sender_id : {type: String, required: true },
  user_id : {type: String, required: true },
  product_id : {type: String, default : "" },
  type : {type: String, required: true }

},options);