默认情况下,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
。这可能吗?
据我所知,目前使用猫鼬实现这一目标的方法是使用虚拟机。在填充虚拟机时,可以将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
})