Mongoose: Populate path using field other than _id(Mongoose:使用_id以外的字段填充路径)
本文介绍了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。在填充虚拟时,您可以将localField和foreignField 指定为您想要的任何值,因此您不再绑定到默认的_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
})
这篇关于Mongoose:使用_id以外的字段填充路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:Mongoose:使用_id以外的字段填充路径
基础教程推荐
猜你喜欢
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- 从快速中间件中排除路由 2022-01-01
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
