我有两个架构,分别是Username和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问题中的解决方案对我不起作用。
修改
UserOrganization 集合
{
"_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
}