node.js - Mongo - 按不是 ObjectId 的值引用其他模式
问题描述
所以理论上,假设我有一个Posts
模式并且想要链接在模式中创建它的用户。传统上我会放入模式
posted_by: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
}
假设用户有一个名为“user_serial_no”的字段,有没有办法可以使用这个其他字段(这将是唯一的)而不是 ObjectId 从帖子中引用用户?
解决方案
你正在寻找的是aggregate.lookup()
更多信息:https ://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-lookup
const result = await Posts.aggregate([
{
'$lookup': {
'from': User.collection.name,
'localField': 'posted_by',
'foreignField': 'user_serial_no',
'as': 'postByUser' // <= Mongoose will create a new field as a result for you
}
},
/*Other options like $projections & $unwind if needed*/
])
推荐阅读
- python - win32com python 异常行为
- java - NullPointerException 错误,有人知道吗?
- php - PHP curl从json文件发送PUT请求
- python - 从 pybullet 理解视图和投影矩阵
- swift - SwiftUI:仅在某些视图上在 iPad 上消失的弹出框
- ios - UIWindow 功能在 Xcode11.3 中不起作用吗?
- azure - 在 Azure 表存储服务中查询 PartitionKey 和 RowKey 语法
- java - Azure HTTPTrigger 发布请求上传文件
- java - IntelliJ 执行失败
- c# - Selenium WebDriver C#:即使元素被禁用,Element.Enabled 也会返回 True