【发布时间】:2022-07-22 01:43:58
【问题描述】:
我正在使用 Mongoose 和 MongoDB。 我有三个模式用户和流派和歌曲。
const userSchema = new Schema({
name: String,
age: String,
favorite_genres: {
type: Schema.Types.ObjectId,
ref: 'Genre'
}
});
const genreSchema = new Schema({
name: String,
songs: {
type: Schema.Types.ObjectId,
ref: 'Song'
}
});
const songSchema = new Schema({
title: String,
artist: String,
length: String,
year: String
});
这些是简单的模式,但它们可以用于这个目的。 因此,当我查询用户时,我想用最喜欢的流派填充文档。但是那里(由于潜在的数据量)不是所有歌曲的ID,而是歌曲的数量。我怎样才能做到这一点?
我尝试了虚拟,但它们并没有按照我想要的方式工作。 我正在寻找的是以下内容:
const user = await User.findById(userID).populate({path: 'favorite_genres', select: 'name', sizeof: 'songs'}).lean()
// or
const user = await User.findById(userID).populate({path: 'favorite_genres', select: ['name', 'songs.length']}).lean()
有人有想法吗?
【问题讨论】:
-
这会给你一个想法吗? stackoverflow.com/questions/33447670/…
标签: javascript node.js mongodb mongoose