Javascript Mongoose:使用非_id的字段填充路径

Javascript Mongoose:使用非_id的字段填充路径,javascript,node.js,mongodb,mongoose,schema,Javascript,Node.js,Mongodb,Mongoose,Schema,默认情况下,mongoose/mongo将使用\u id字段填充路径,并且似乎无法将\u id更改为其他内容 以下是我的两个模型,它们通过一对多关系连接: const playlischema=new mongoose.Schema({ 外部ID:String, 标题:字符串, 视频:[{ 类型:mongoose.Schema.Types.ObjectId, 参考:“视频”, }], }); const videoSchema=新的mongoose.Schema({ 外部ID:String, 标

默认情况下,mongoose/mongo将使用
\u id
字段填充路径,并且似乎无法将
\u id
更改为其他内容

以下是我的两个模型,它们通过一对多关系连接:

const playlischema=new mongoose.Schema({
外部ID:String,
标题:字符串,
视频:[{
类型:mongoose.Schema.Types.ObjectId,
参考:“视频”,
}],
});
const videoSchema=新的mongoose.Schema({
外部ID:String,
标题:字符串,
});

通常,在查询播放列表时,您只需使用
.populate('videos')
填充
视频
,但在我的情况下,我希望使用
外部id
字段,而不是默认的
\u id
。这可能吗?

据我所知,目前猫鼬实现这一目标的方法是使用。在填充虚拟现实时,您可以将
localField
foreignField
指定为您想要的任何内容,这样您就不再将默认的
\u 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
virtual以获取引用的视频文档

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
  })

这可能会有所帮助,但如果不使用$lookup aggregation,我认为这是虚拟的,而不是虚拟的