title: Mongoose populate embedded document in cascade
body: <p>I am modeling a 'friends' relationship between the user of my micro-blog app. It looks something like this:</p>
  
  <p><em>in the user.js file</em></p>
  
  <pre><code>var db = require('mongoose')
  , Schema = db.Schema
  , ObjectId=Schema.ObjectId;
  
  var userSchema = new Schema({
      name:{firstname:String,surname:String},
      birthdate:String,
      email:String,
      posts: [new Schema({
          timestamp:Date,
          post:{type: ObjectId, ref: 'Post'}
      })],
      friends: [new Schema({
          friend: {type:ObjectId, ref:'User'}
      })]
  });
  
  module.exports = db.model('User', userSchema);
  </code></pre>
  
  <p><em>in the post.js file</em></p>
  
  <pre><code>var db = require('mongoose')
    , Schema = db.Schema,
    ObjectId=Schema.ObjectId;
  
  var postSchema = new Schema({   
          title:String,
          content:String,
  });
  
  module.exports = db.model('Post', eventSchema);
  </code></pre>
  
  <p>What I want to achieve is to get all the current user's friends, with their posts array of embedded document, already populated. I clumsily tried with this function:</p>
  
  <pre><code>function getUserFriendsPost(req, res) {
      var count = 0;
      var output = new Array();
      User.findOne({
          _id: req.params.id
      }, function(err, user) {
          for (var i = 0; i &lt; user.friends.length; i++) {
              User.findOne({
                  _id: user.friends[i].friend
              }).populate('posts.post').exec(function(err, post) {
                  output.push(post);
                  count++;
                  if (count==user.friends.length) {
                      res.send(output);
                  }
              });
          }
  
      });
  
  }
  </code></pre>
  
  <p>What I get instead is the friends array correctly returned but the element of the posts having value of null, like this:</p>
  
  <pre><code>[
      {
          "_id": "4fd5e5f3e45fd10100000004",
          "birthdate": "11/11/1911",
          "email": "blablabla@gmail.com",
          "friends": [],
          "posts": [
              {
                  "timestamp": "2012-04-12T16:47:14.576Z",
                  "post": null,
                  "_id": "4f870712c488cf0100000081"
              },
              {
                  "timestamp": "2012-04-12T16:48:42.282Z",
                  "post": null,
                  "_id": "4f87076ac488cf01000000a3"
              },
              {
                  "timestamp": "2012-04-12T16:56:26.062Z",
                  "post": null,
                  "_id": "4f87093ac488cf0100000117"
              }
          "name": {
              "firstname": "John",
              "surname": "Doe"
          }
      }
  ]
  </code></pre>
  
  <p>Is there something that I am overlooking the in populate mechanism or should I proceed with a different approach?
  Thank you</p>