javascript - mongoose 中的 $lookup 返回空
问题描述
我有两个模式,即用户名和 UserOrganization 模式,如下所示:
const UsernameSchema = new Schema ({
username: {type: String, unique: true},
displayUsername: {type: String},
type: {type: String},
refId: {type: String},
current: {type: Boolean},
forward: {type: Date}
});
module.exports = mongoose.model('Username', UsernameSchema);
const UserOrganizationSchema = new Schema({
userId: {type: String},
orgId: {type: String},
roles: [{type: String}],
});
module.exports = mongoose.model('UserOrganization', UserOrganizationSchema);
这里 UserOrganization 架构的 orgId 等于 Username 架构的 refId。现在,当我尝试以下代码时:
Username.aggregate([
{
$lookup: {
from: 'UserOrganization.collection.name',
localField: 'refId',
foreignField: 'orgId',
as: 'test',
},
}])
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error)
)}
console.log(data) 返回
[{ _id: 5c64f9914c22010ee00fb47f,
username: 'sub',
displayUsername: 'sub_syd',
refId: '5c64f9914c22010ee00fb47c',
type: 'org',
current: false,
__v: 0,
test: [] }]
其中测试字段为空。我的代码有问题吗?
提前致谢。
PS:以前类似 StackOverflow 问题的解决方案对我不起作用。
编辑
用户组织集合
{
"_id" : ObjectId("5c663050dfc59c2428a6662a"),
"roles" : [
"member"
],
"userId" : "5c62600a63c3c52e3135d20b",
"orgId" : "5c628478ca7cc030c86a1a6c",
"__v" : 0
}
用户名集合:
{
"_id" : ObjectId("5c628478ca7cc030c86a1a6e"),
"username" : "test1",
"displayUsername" : "test_1",
"refId" : "5c628478ca7cc030c86a1a6c",
"type" : "organization",
"current" : false,
"__v" : 0
}
解决方案
推荐阅读
- node.js - 如何在sequelize中根据货币转换价格?
- excel - 如果 Excel 中唯一值的状态不同,则排除 sumifs 中的添加
- docker - yocto 作物容器的 PATH 变量不能被修改
- java - 如何使用存储在 hdfs 中的 jceks 文件连接到 aws sqs 队列和 s3
- html - 如何使第一列的内容不会溢出到 CSS 中的第二列?
- user-interface - 自定义 Mautic 导航
- c# - 如何在 DevExpress PropertyGridControl 中手动显示“Canvas.Top”属性?
- android - keytools -exportcert -list -v -alias androiddebugkey -keystore ~/.android/debug.keystore (适用于 windows)
- docker - 如果我有多个,如何泊坞注册表镜像?
- webrtc - 如何在 Agora.io 中全局访问 Camara 和 Mic