Sort an nested array in mongoose

2020-03-06 14:36发布

问题:

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:

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 
});