2017-08-08 69 views
0

我试图从我的Mongo实例中提取数据,该数据将显示给定帐户ID的所有用户。用户可以将多个账户的一部分,所以我目前得到了我的蒙戈模型这种结构:MongoDB在外键上聚合两个集合

的usermodel:

username: { 
     type: String, 
     required: true, 
     unique: true, 
     lowercase: true 
    }, 
    name: { 
     type: String, 
     required: true 
    }, 
    password: { 
     type: String, 
     required: true 
    }, 
    email: { 
     type: String, 
     required: true, 
     unique: true 
    }, 

UsersToAccountModel:

{ 
    user: { 
     type: Schema.Types.ObjectId, 
     ref: 'users' 
    }, 
    userGroup: { 
     type: Schema.Types.ObjectId, 
     ref: 'userGroups' 
    }, 
    account: { 
     type: Schema.Types.ObjectId, 
     ref: 'accounts' 
    }, 
    default: { 
     type: Boolean, 
     default: null 
    } 
} 

的UsersToAccount模型集合保存的ObjectId用户,帐户和userGroup在其字段中,因此充当链接集合。

对于与UsersToAccount集合中给定帐户ID匹配的每个userId,我想要该ID并查询用户表并将其返回。在MySQL中的查询是:?

SELECT * FROM userToAccounts U2A LEFT JOIN用户U ON u.id = u2a.userId WHERE u2a.account = $帐户ID

谁能帮我在这里,我已经厌倦了,但聚集我不是很远。

这里是我的尝试,到目前为止这是不工作:

const users = await this.userToAccountModel.aggregate(
       { 
        $match: { account: requestVars.account }, 
       }, 
       { 
        $lookup : { from: "users", localField: "_id", as: "userData", foreignField: "user"} 
       } 
      ); 

感谢

回答

0

首先,$lookup阶段的语法如下:

{ 
    $lookup: { 
     from: <collection to join>, 
     localField: <field from the input documents>, 
     foreignField: <field from the documents of the "from" collection>, 
     as: <output array field> 
    } 
} 

所以,我认为你需要交换localFieldforeignField值。其次,aggregate()期望一个数组。

const users = await this.userToAccountModel.aggregate([ 
    { 
     $match: { account: requestVars.account }, 
    }, 
    { 
     $lookup : { from: "users", localField: "user", foreignField: "_id", as: "userData" } 
    } 
]);