首页 > 解决方案 > 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
}

标签: javascriptnode.jsmongodbmongoose

解决方案


推荐阅读