Sort an nested array in mongoose

前端 未结 1 445
梦如初夏
梦如初夏 2021-01-07 01:21

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

相关标签:
1条回答
  • 2021-01-07 01:53

    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 
    });
    
    0 讨论(0)
提交回复
热议问题