我在UserController中去调用MusicController
UserController
static async getUserLikeMusic(req, res) {
let music = new MusicController();
try {
const userId = req.userId; // 获取存储在请求对象中的用户 ID
// 查询用户信息
const user = await UserModel.findById(userId)
if (user) {
const likeMusic = user.like_music;
let musicInfoList = [];
// 使用 Promise.all 来并行获取所有音乐信息
const promises = likeMusic.map(async musicId => {
console.log(musicId, "000")
try {
const musicInfo = await MusicController.getInfoByMusicId(req, musicId);
musicInfoList.push(musicInfo);
} catch (error) {
console.error(`获取音乐信息失败--: ${error.message}`);
}
});
await Promise.all(promises);
res.send(musicInfoList);
return;
}
return res.status(404).json({ error: '用户不存在!' });
return
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
}
MusicController
class MusicController {
static async getInfoByMusicId(req, musicId) {
console.log(musicId,"----------")
try {
const musicInfo = await MusicModel.findById(musicId);
console.log(musicInfo)
if (!musicInfo) {
throw new Error('音乐不存在!');
}
return musicInfo;
} catch (error) {
throw new Error(`获取音乐信息失败: ${error.message}`);
}
}
}