Mongoose:使用 _id 以外的字段填充路径

问题描述 投票:0回答:2

默认情况下,mongoose/mongo 将使用

_id
字段填充路径,并且似乎无法将
_id
更改为其他内容。

这是我的两个以一对多关系连接的模型:

const playlistSchema = new mongoose.Schema({
  externalId: String,
  title: String,
  videos: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Video',
  }],
});

const videoSchema = new mongoose.Schema({
  externalId: String,
  title: String,
});

通常,在查询播放列表时,您只需使用

videos
填充
.populate('videos')
,但就我而言,我想使用
externalId
字段而不是默认的
_id
。这可能吗?

javascript node.js mongodb mongoose schema
2个回答
8
投票

据我所知,目前用 mongoose 实现这一点的方法是使用 virtuals。填充虚拟时,您可以将

localField
foreignField 
指定为您想要的任何内容,这样您就不再将默认的
_id
绑定为
foreignField
。有关此的更多详细信息此处

对于您问题中描述的场景,您需要将虚拟添加到

playerlistSchema
,如下所示:

playlistSchema.virtual('videoList', {
  ref: 'Video', // The model to use
  localField: 'videos', // The field in playerListSchema
  foreignField: 'externalId', // The field on videoSchema. This can be whatever you want.
});

现在,每当您查询播放器列表时,您都可以填充

videoList
虚拟来获取引用的视频文档。

PlaylistModel
  .findOne({
    // ... whatever your find query needs to be
  })
  .populate('videoList')
  .exec(function (error, playList) {
    /* if a playList document is returned */
    playList.videoList; // The would be the populated array of videos
  })

0
投票

2024 - Mongoose 版本 8

有一个更好、更简单的方法来实现这一点:

  PlaylistModel.find()
    .populate({
      path: 'videos',
      model: 'Video',
      select: 'title',
      foreignField: 'externalId',
    })
  • path:指定您想要的公告架构中的字段 填充。
  • model:指定用于人口的模型。
  • select:指定要从引用文档中选择的字段。
  • foreignField:指定引用模型中的字段(在本例中为视频),用于与本地字段(playlistSchema 中的视频)匹配以填充引用。 (而不是默认的
    _id
© www.soinside.com 2019 - 2024. All rights reserved.