title: Mongoose nested reference population
body: <p>I'm having trouble understanding some of the concepts behind mongoose's <a href="http://mongoosejs.com/docs/populate.html" rel="nofollow">populate</a> methods. I had an embedded approach working first, although, as I feared a big overhead of data and out-of-sync documents going around I tried changing the paradigm to <code>ref</code> other documents.</p>
  
  <p>My Schema is similar to the following (removed irrelevant properties):</p>
  
  <pre><code>var userSchema = mongoose.Schema({
      name: {type: String, default:''},
      favorites:{ 
          users:[{type: Schema.Types.ObjectId, ref: this}],
          places:[{type: Schema.Types.ObjectId, ref: PlaceSchema}]
      }
  });
  
  module.exports = mongoose.model('User', userSchema);
  </code></pre>
  
  <p>Now I'm trying to get a <code>User</code>'s <code>favorites</code> like this:</p>
  
  <pre><code>User.findOne({_id: currentUser}).exec(function(err, user){
    console.log(user);
    if (err)
      throw err;
  
    if(!user){
      console.log("can't find user");
    }else{ // user found
      user.populate('favorites.users');
      user.populate('favorites.places');
  
      // do something to the 'user.favorites' object
  
    }
  });
  </code></pre>
  
  <p>Although this doesn't work as intended, as both <code>user.favorites.users</code> and <code>user.favorites.places</code> come up undefined.</p>
  
  <p>I thought that I could populate as above, but apparently, that's not the case. From what I read, I must be missing something indicating (maybe) the model of the <code>ref</code>'ed document? This flow is very new to me and I'm kinda lost.</p>
  
  <p>Is there anyway I can get an array of <code>users</code> and <code>places</code> by populating my query result as above? I tried <code>populate</code> chained with <code>exec</code> and it doesn't work either. Is there a better way to achieve this result?</p>
  
  <p>EDIT: In case it's needed, in the DB, a <code>User</code> document shows up as:</p>
  
  <pre><code>{
    "_id": "56c36b330fbc51ba19cc83ff",
    "name": "John Doe",
    "favorites": {
      "places": [],
      "users": [
        "56b9d9a45f1ada8e0c0dee27"
      ]
    }
  }
  </code></pre>
  
  <p>EDIT: A couple more details... I'm currently storing/removing the reference ObjectIds like this (note targetID is a String):</p>
  
  <pre><code>user.favorites.users.push({ _id: mongoose.Types.ObjectId(targetID)});
  user.favorites.users.pull({ _id: mongoose.Types.ObjectId(targetID)});
  </code></pre>
  
  <p>Also, I need to populate the <code>users</code> and <code>places</code> with their respective documents <strong>aswell</strong>, I think that might not be clear in my original question.</p>