title: Mongoose JS relationships
body: <p>So I'm making an express app that has a user model and a post model. The users have many posts and each post belongs to a user. Here are the models</p>
  
  <p>user.js</p>
  
  <pre><code>var mongoose = require('mongoose');
  var Schema = mongoose.Schema;
  
  var userSchema = new Schema({
    _id : Number,
    username: String,
    password: String,
    admin: Boolean,
    posts: [{
      type: Schema.Types.ObjectId,
      ref: 'Post'
    }]
  });
  
  module.exports = mongoose.model('User', userSchema);
  </code></pre>
  
  <p>post.js</p>
  
  <pre><code>var mongoose = require('mongoose');
  var Schema = mongoose.Schema;
  
  var postSchema = new Schema({
    title: 'string',
    content: 'string',
    _author: {
      type: Number,
      ref: 'User'
    }
  });
  
  module.exports = mongoose.model('Post', postSchema);
  </code></pre>
  
  <p>First of all I'm not sure if that is the best way to associate the two models so that post belongs to user but that is what it looked like in the mongoose documentation here <a href="http://mongoosejs.com/docs/populate.html" rel="nofollow">http://mongoosejs.com/docs/populate.html</a></p>
  
  <p>Now what I want to do is when I hit this route</p>
  
  <pre><code>router.post('/', function(req, res){
    var post = new Post(req.body);
  
  
    console.log(author.posts);
  
    post.save(function(err){
      if (err){
        return res.send(err);
      }
  
      res.send({message: 'Post added!'});
    });
  });
  </code></pre>
  
  <p>I want the post to be inserted into the user post array. I have been looking through the documentation and believe that the populate method is the way to do this but I can't seem to figure out how to use it and if it actually inserts that post into the authors post array.</p>
  
  <p>I tried this but it didn't seem to do what I wanted</p>
  
  <pre><code>Post.findOne({
      title: "The nip"
    })
    .populate('_author')
    .exec(function (err, post) {
      if (err) return handleError(err);
      console.log('The creator is %s', post._author.username);
    });
  </code></pre>
  
  <p>Any advice on how to get the created post into its authors posts array would be much appreciated!</p>