首页 > 解决方案 > 如何从填充的文档中选择字段,但在父文档上使用选择?

问题描述

我正在尝试实现类似 Spotify API 的字段限制

items(a,b(c,d))会选择items.a、items.bc、items.bd

就我而言,我的主文档(tracks.items)中有一个填充字段(add_by)

"tracks": {
    "href": "https://api.spotify.com/v1/playlists/5e8a3a6e263b6431749b1c2f/tracks",
    "items": [
      {
        "is_local": false,
        "_id": "5e8a3d7214fc7751301abd87",
        "added_at": "2020-04-05T20:20:02.773Z",
        "added_by": {
          "type": "artist",
          "_id": "5e8a399a263b6431749b1c27",
          "name": "Artist Account",
          "uri": "spotify:user:5e8a399a263b6431749b1c27",
          "id": "5e8a399a263b6431749b1c27"
        }
     ]
}

我想通过发送限制查询来选择填充字段(add_by)内的字段,tracks.items.added_by(type,name) 但不必手动解析字符串以在填充上调用猫鼬的选择对象,因为很难解析许多填充字段的字符串

我的意思是,在我的代码中我有这个

Playlist.findById(playlistId, queryObject)
    .populate([
      {
        path: 'tracks.items.track',
        select: populationFields,
        populate: [
          {
            path: 'album',
            select:
              'album_type artists id images name type uri external_urls href',
            populate: {
              path: 'artists',
              select: 'external_urls href id name type uri'
            }
          },
          {
            path: 'artists',
            select: 'external_urls href id name type uri'
          }
        ]
      },
      {
        path: 'tracks.items.added_by',
        select: 'name id type uri href'
      }
    ]),
  queryParams
)

我想轻松实现上面显示的字段限制查询

标签: mongoose

解决方案


推荐阅读