2

i have a PlaylistShema with an array or musics. In this array of musics I have an ObjectId (who ref to a Music collection), an addedAt and a title.

PlaylistShema

var PlaylistSchema = new Schema({
  title: {type : String, default : '', trim : true},
  user: {type : Schema.ObjectId, ref : 'User'},

  musics : [{ 
    musicId : {type : Schema.ObjectId , ref : 'Music'},
    title : {type : String},
    addedAt : {type : Date, default : Date.now}
  }],

  tags : { type : [], get : getTags, set : setTags},
  createdAt  : {type : Date, default : Date.now}
})

i have a statics to load a playlist :

Load function

  load: function (id, cb) {
    this.findOne({ _id : id })
      .populate('user', 'name email username')
      .populate('musics.musicId')
      .exec(cb)
  }

i want to sort my musics by addedAt... but i can't do .populate('musics.musicId', { sort: { 'addedAt': 'desc' } }) because this is not where addedAt is...

i'm very confused with populate when it comes to nested array...

thanks !

MusicShema

var MusicSchema = new Schema({
  title: {type : String, default : '', trim : true}
})

1 Answer 1

6

You can't sort an array directly in Mongoose. You can clone the data and sort it as a JavaScript object by using toObject (documentation) and the Array sort method:

Playlist.load(function(err, playList) {
    var pl = playList.toObject();
    pl.musics.sort(function(m1, m2) { return m1.addedAt - m2.addedAt; });
    // pl contains the playlist now 
});
Sign up to request clarification or add additional context in comments.

4 Comments

hum okay ! that's why ! Thanks
hi, I have a similar model. When I populate my "musics" field I don't be able to get the "name" or "description" of the ref record. How can I do that?
You should probably ask a new question.
@WiredPrairie, about "can't sort arrays", is that the reason why this is not working? stackoverflow.com/questions/32191086/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.