Mongoose:使用_id以外的字段填充路径 [英] Mongoose: Populate path using field other than _id

查看:66
本文介绍了Mongoose:使用_id以外的字段填充路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,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。这可能吗?

推荐答案

据我所知,目前Mongoose实现这一点的方式是使用virtuals。在填充虚拟时,您可以将localFieldforeignField 指定为您想要的任何值,因此您不再绑定到默认的_idforeignField。有关此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
  })

这篇关于Mongoose:使用_id以外的字段填充路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆