【问题标题】:Mongoose: Populate path using field other than _idMongoose:使用 _id 以外的字段填充路径
【发布时间】:2020-07-20 04:19:22
【问题描述】:

默认情况下 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,
});

通常,在查询播放列表时,您会使用.populate('videos') 填充videos,但在我的情况下,我想使用externalId 字段而不是默认的_id。这可能吗?

【问题讨论】:

标签: javascript node.js mongodb mongoose schema


【解决方案1】:

据我所知,目前使用 mongoose 实现此目的的方法是使用 virtuals。填充虚拟时,您可以将localFieldforeignField 指定为您想要的任何内容,因此您不再绑定到默认的_id 作为foreignField。有关此here 的更多详细信息。

对于您问题中描述的场景,您需要将虚拟添加到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
  })

【讨论】:

  • 我认为它是虚拟的而不是虚拟的
猜你喜欢
  • 2021-10-04
  • 2021-09-27
  • 1970-01-01
  • 2017-09-17
  • 2012-01-22
  • 2017-05-21
  • 2023-04-08
  • 2018-09-05
  • 1970-01-01
相关资源
最近更新 更多