Skip to content

Instantly share code, notes, and snippets.

@iamkale
Created July 13, 2012 13:05
Show Gist options
  • Save iamkale/3104792 to your computer and use it in GitHub Desktop.
Save iamkale/3104792 to your computer and use it in GitHub Desktop.
Populate in mongoose
var mongoose = require('mongoose');
var Event = mongoose.model('Event');
var Calendar = mongoose.model('Calendar');
function eventController(app) {
app.get('/calendar/:calendarid', function (req, res) {
Calendar
.findOne({ _id:req.params.calendarid })
.populate('events')
.exec(function (err, data) {
console.log("executing populate");
if (err) {
return res.json({error:err})
}
return res.json(data)
})
});
exports.boot = eventController;
// Calendar model/schema in one file
exports.boot = function(mongoose) {
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var Calendar = new Schema({
creator : { type: Schema.ObjectId, ref: 'User'},
name : { type: String, index:true },
description : String,
events : [{ type: Schema.ObjectId, ref: 'Event'}],
group: [{ type: Schema.ObjectId, ref: 'Group'}],
date : { type : Date, default:Date.now }
});
mongoose.model('Calendar', Calendar);
}
// And in another file the event model/schema
exports.boot = function(mongoose) {
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var Event= new Schema({
creator : { type: Schema.ObjectId, ref: 'User'},
name : { type: String, index:true },
description : String,
attendees : [{ type: Schema.ObjectId, ref: 'User'}],
calendar : { type: Schema.ObjectId, ref: 'Calendar'},
date : { type: Date, default: Date.now}
});
mongoose.model('Event', Event);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment