【问题标题】:Mongoose Get only size of a arrayMongoose 只获取数组的大小
【发布时间】: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()

有人有想法吗?

【问题讨论】:

标签: javascript node.js mongodb mongoose


【解决方案1】:

看看我附上的链接。这是一个类似的问题,我想你会在那里找到你的答案。 You can find Your answer here

【讨论】:

    猜你喜欢
    • 2019-02-07
    • 2020-07-24
    • 2016-05-03
    • 2015-11-04
    • 1970-01-01
    • 2020-07-29
    • 2013-02-26
    • 2020-02-02
    • 2023-04-06
    相关资源
    最近更新 更多