首页 文章

如何将mongoose查询的结果保存到变量中

提问于
浏览
0

我试图通过循环播放专辑中的歌曲列表,查找相关歌曲并尝试保存到阵列中供以后使用,将一些对象保存到数组中 . 有没有办法实现这个目标?

我需要一些使用猫鼬的解释 .

exports.playlistPlayer = function (req, res, next) {
Playlist.findById({
    _id: req.body.playlist._id
}, (err, playlist) => {

    var customAlbum = []; //This variable it's inside the same block i believe


    playlist.songs.forEach(function (song) {
        Song.findById({
            _id: song.song_id
        }, (err, songs) => {

            var customSong = {
                title: songs.title,
                time: songs.time,
                source: songs.source,
                song_id: songs._id
            }
            customAlbum.push(customSong)
            console.log(customAlbum) //it works here
        });

    });

    console.log(customAlbum) //it returns an empty array here where i need the data

 });
};

1 回答

  • 0

    问题是 findById 方法也是异步的 . 我建议你在javascript中学习promises . 一种可能的解决方案是使用ES7的async / await功能:

    // asynchronous function
    exports.playlistPlayer = async (req, res, next) => {
      // wait for the findById method promise to resolve
      const playlist = await Playlist.findById({
        _id: req.body.playlist._id
      })
    
      // wait for finding all songs in db whose id's are in
      // the playlist.songs array
      const songs = await Song.find({
        _id: { $in: playlist.songs }
      })
    
      // create the customAlbum by using the map method to
      // tramsform the song objects to the required form
      const customAlbum = songs.map(song => ({
        title: song.title,
        time: song.time,
        source: song.source,
        song_id: song._id
      }))
    
      // and there you should now have your customAlbum array
      console.log(customAlbum)
    
      // now you can use it for example
      // to return a response to the client:
      // res.json(customAlbum)
    }
    

相关问题