const artistSchema = new Schema({
name: String,
});
const albumSchema = new Schema({
name: String,
artists: [{type: ObjectId, ref: 'Artist'}]
});
const trackSchema = new Schema({
title: String,
album: {type: ObjectId, ref: 'Album'},
visits: Number,
});
graphql看起来像这样:
tracks {
title
visits
album {
name
artists {
name
}
}
}
如何获得仅具有艺术家ID的访问量最大的曲目?
我尝试使用Track.find({'album.artists.id': artistId})
。无法正常工作。
答案 0 :(得分:0)
万一有人需要它:
const artistId = "...";
const limit = 5;
const artistObjectId = mongoose.Types.ObjectId(artistId);
return await Track.aggregate([
{
$lookup: {
from: "albums",
localField: "album",
foreignField: "_id",
as: "album"
}
},
{
$match: {
"album.artists": artistObjectId
},
},
{
$sort: {
visits: -1
}
},
{
$limit: limit
},
{
$lookup: {
from: "artists",
localField: "album.artists",
foreignField: "_id",
as: "album.artists"
}
},
]);