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"}
}
);
感谢