0

I have problem trying to do a sort by date of updated_at "post" (subdocument), with the code below i see the posts in order of creation. I need sort by date of updated.

var postSchema = new mongoose.Schema({
    post: String,
    created_at: { type: Date, default: Date.now },
    updated_at: Date
});

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    posts: [postSchema]
});


app.get("/val",isLoggedIn, function(req, res){
    var aca = req.user._id; 
    User.findById({_id: aca},function(err, myposts){
       if(err){
           console.log(err);
       } else {
           res.render("index", {dataposts:myposts});
       }
    });
    });
Paolo
  • 1
  • See https://stackoverflow.com/questions/31382656/mongoose-subdocument-sorting – Mickael B. May 01 '20 at 15:34
  • thanks for your response. Do you think is there any way to include sort in this part of the GET. app.get("/val",isLoggedIn, function(req, res){ var aca = req.user._id; User.findById({_id: aca},function(err, myposts){ if(err){ console.log(err); } else { res.render("index", {dataposts:myposts}); } }); }); – Paolo May 01 '20 at 16:19
  • Maybe you can use `User.findById({_id: aca}).sort({'posts.updated_at': 'desc'}).exec(function(err, myposts) { ... });` – Nayan May 01 '20 at 18:36
  • Thanks I had try it, but it doesn't work. zero error but its doesn't sort it. I don't know why. – Paolo May 01 '20 at 20:42
  • What is the version of mongoDB, mongoose you are using? – Sohan May 02 '20 at 11:17

1 Answers1

0

I would suggest following, using $order_by

User.findById({ $query : {_id: aca},$orderby: {updated_date: -1} })

In latest versions of mongoose this should work,

User.findById({_id: aca}).sort({updated_at:-1}).exec(function(err, myposts) { ... });

Sohan
  • 6,252
  • 5
  • 35
  • 56