Mongoose Populate

/ Edit this post

I found this to be extremely helpful recently when dealing with MongoDB NodeJS joins. Pay close attention to this = "stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]"

var mongoose = require('mongoose')  
  , Schema = mongoose.Schema

var personSchema = Schema({  
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({  
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

var Story  = mongoose.model('Story', storySchema);  
var Person = mongoose.model('Person', personSchema);  

then use .populate() to grab the story's ref

Story  
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {
  if (err) return handleError(err);
  console.log('The creator is %s', story._creator.name);
  // prints "The creator is Aaron"
})