title: How to access attributes of an embedded document (DBRef-like) from a Schema method with Mongoose?
body: <p>I am building a nodejs app with express and mongoose/mongodb. </p>
  
  <p>In order to manage user roles (a user may have 0-n roles), I decided to implement a User schema and a separate Role schema and tie them together like DBRefs and using mongoose populate capability to get from one to the other easily. I chose this structure because I thought this was the best way to answer things like: "Get me a list of users that have X role" or "Get me a list of users whose Y role is set to expire soon".</p>
  
  <p>These are stripped down versions of my schemas for role and user:</p>
  
  <pre><code>RoleSchema = new Schema {
    _user: { type: Schema.ObjectId, ref: 'User' }
    type: String
    expiration: { type: Date, default : '0' }
  }
  
  UserSchema = new Schema {
    email: { type: String, index: { unique: true }}      
    roles : [{ type: Schema.ObjectId, ref: 'Role' }]
  }
  </code></pre>
  
  <p>With this, I am able to create/fetch/populate users and roles from within my express scripts without a problem. When I want to add a role to a user, I create the role, save it and then push it to the roles array of the user and then save the user. So, what happens in mongoDB is that each schema has its own collection, and they point to each other through an id field. </p>
  
  <p>Now, what I want to do next is implement boolean-type methods on my schema to check for role-related issues, so that I can do things like </p>
  
  <pre><code>if(user.isActiveSubscriber())
  </code></pre>
  
  <p>I thought that I would be able to accomplish this simply by adding a method to my User schema, like this:</p>
  
  <pre><code>UserSchema.method "isActiveSubscriber", -&gt;
    result = false
    now = new Date()
    @roles.forEach (role) -&gt;
      result = true  if role.type is "SUBSCRIBER" and role.expiration &gt; now
   result
  </code></pre>
  
  <p>My problem is that roles are coming out with empty attributes. I suppose it makes sense, since my user collection only has the id of the role but the actual attributes are stored in another collection.</p>
  
  <p>So, here go the questions:</p>
  
  <p>a) Is there a way to load the roles attributes from within my user schema method? 
  I tried calling populate inside the method, but got an error that the user object doesnt know any populate method. I also tried doing a Role.findById() from inside the method but also get an error (tried with Role and RoleSchema)</p>
  
  <p>b) In case there is not a way ... should I simply add the code to check in my scripts? I hate having to put this kind of logic mixed with application logic/flow. Is there a better option?</p>
  
  <p>c) Was it a bad idea to separate these collections in two? Am I completely missing the point of NoSQL? Would it be better if roles were simply an array of embedded documents stored as part of the user collection?</p>