默认情况下,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
。这可能吗?
据我所知,目前用 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
})
2024 - Mongoose 版本 8
有一个更好、更简单的方法来实现这一点:
PlaylistModel.find()
.populate({
path: 'videos',
model: 'Video',
select: 'title',
foreignField: 'externalId',
})
_id
)