0

I have three models. And i need to get the admin group name of a user

User

  var userSchema = new mongoose.Schema({
    // ...
    roles: {
      admin: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' }, // path 1
    },
 });

Admin

  var adminSchema= new mongoose.Schema({
    // ...
    groups: [{ type: String, ref: 'AdminGroup' }], // path 2
  });

AdminGroup

  var adminGroupSchema = new mongoose.Schema({
    // ...
    name: { type: String, default: '' }, // need to get this field
  });

In Mongoose

User.findById(req.user._id)
    .populate({path: 'roles.admin', populate:{ path: 'groups'}})
      .exec(function (err, adminGroups) {...}

When I try to call in my template {{adminGroups.name}} it returns the name of Admin model, which also has a name field, instead of AdminGroup model.
I am usung Mongoose 4.9.0 so it must have support for deep population. Thanks.

ASem
  • 142
  • 3
  • 16

1 Answers1

1

You are using findById and populating its fields.

You're not getting back adminGroups but ONE user who may have roles.admin that may contain an array of groups. I use the word may because those other fields might not be populated if they do not exist. However, you'll still get back one User document, if there is one.

User.findById(req.user._id).populate({
    path: 'roles.admin', 
    populate: { 
        path: 'groups'
    }
}).exec(function (err, user) {
    console.log(err, user); // see what it prints out
    console.log(user.roles.admin.groups[0].name);
});

And shouldn't it be AdminGroup instead of AccountGroup in your schema definition?

Mikey
  • 6,728
  • 4
  • 22
  • 45
  • the 1st it prints out whole User document with `groups: [Object],` the second is now returnig Root (what i needed). So the ploblem is with templates? How shild I call it there? – ASem Aug 16 '17 at 01:09
  • @ASem Pass the `user` object to your view and do `{{user.roles.admin.groups[0].name}}` maybe? – Mikey Aug 16 '17 at 01:17
  • It returns me an error ` Expecting 'ID', got 'INVALID' ` I im using Handlebars. – ASem Aug 16 '17 at 01:25
  • 1
    @ASem According to this [answer](https://stackoverflow.com/a/8044689/1022914), it should be `user.roles.admin.groups.0.name` or `user.roles.admin.groups.[0].name`. – Mikey Aug 16 '17 at 01:31
  • 1
    Wow thanks you helped me a lot. That was really a mess with those models. – ASem Aug 16 '17 at 01:39