1

This is the Schema:

var userschema = new mongoose.Schema({

  user: String,
  messages: [{ 

              title: String,
              author: String,
              message: String,
              date: { type: Date, default: Date.now },

           }],

});

I'm trying to show all the users' message in a single page ordered by date. I know how for example show all the messages of a specific user, but if I have multiple users, I don't know how to classificate their message by date using mongoose. Is there any way to do this...?

Thank's advance!

MrMangado
  • 993
  • 4
  • 10
  • 26

1 Answers1

1

Use the aggregation framework and $unwind the messages array so that you can $sort them all by date:

Users.aggregate([
    {$unwind: '$messages'},
    {$sort: {'messages.date': 1}}
], function (err, result) {
    console.log(result);
}
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • If I want to do that, but selecting some specific users, should I change some thing? – MrMangado Jan 15 '13 at 20:18
  • @MrMangado Add a [`$match`](http://docs.mongodb.org/manual/reference/aggregation/#_S_match) operator to the pipeline to filter the docs. – JohnnyHK Jan 15 '13 at 20:52
  • Is possible to use the `$match` operator with an array? – MrMangado Jan 15 '13 at 20:58
  • @MrMangado You'd include it after the `$unwind` so that `messages` is no longer an array when it's applied. – JohnnyHK Jan 15 '13 at 21:07
  • But, I meant that if I could search the messages of specific users, using `$match`, with an array that has the `_id`s of the users. – MrMangado Jan 16 '13 at 13:06
  • @MrMangado Sure, you'd use `$match` with an [`$in`](http://docs.mongodb.org/manual/reference/operator/in/#_S_in) operator for that. – JohnnyHK Jan 16 '13 at 13:31
  • It works perfectly :D But, instead to receive a whole user schema with the `messages`' schema within it, is posible to get only the `messages`' schema? – MrMangado Jan 16 '13 at 20:39