Mongoose子文件深入人口

时间:2017-12-14 20:36:40

标签: node.js mongodb mongoose

我试图用Nodejs和mongoose学习Mongdb。 我不能成功地“深入人心化”#34;我的mongoose查询。

这是我的数据库:

companies: [{
    name:"test"
    users:[{
      name:"user1",
      role: { type: Schema.Types.ObjectId, ref: 'Role' } //5a32a0b0c592bb82f67602fa
    }]
  }],
roles:[{_id:"5a32a0b0c592bb82f67602fa",name:"ADMIN",label:"Administrator"}]

我想提取用户" user1"及其作用" ADMIN"公司"测试" 这是我的问题:

return this.companyModel.findOne({
        name: companyName,
        users: { $elemMatch: user }
    }).then((res: ICompany) => {
   if (!res) {
     throw new ResourceNotFound('User Not Found');
    }
   try {
     return res.users[0];
   }
   catch (e) { throw new ServerError('Server error'); }
 });

这是查询的输出:

{
  "_id": "5a32b2fed9d8579b906fb95d",
  "role": "5a32a0b0c592bb82f67602fa", <-- I need to populate this field
  "name": "user1"
}

像这样:

{
  "_id": "5a32b2fed9d8579b906fb95d",
  "role": {_id:"5a32a0b0c592bb82f67602fa",name:"ADMIN",label:"Administrator"},
  "name": "user1"
}

我如何填充字段&#34;角色&#34;? 我试过几次&#34;填充&#34;但我没有成功!

修改

我找到了以下解决方案:

return this.companyModel.findOne({
        name: companyName,
        users: { $elemMatch: user }
    }).then((res: ICompany) => {
   if (!res) {
     throw new ResourceNotFound('User Not Found');
    }
   try {
     return this.roleModel.populate(res.users[0], { "path": "role" }).then(fullUser => {
                return fullUser;
     })
   }
   catch (e) { throw new ServerError('Server error'); }
 });

这是实现我需要的更好方式还是最优雅的方式?

1 个答案:

答案 0 :(得分:0)

您是否阅读过$lookup。这可以帮助你。