Skip to content

Instantly share code, notes, and snippets.

Created June 23, 2014 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/b7b6d6752aabdd1f9b59 to your computer and use it in GitHub Desktop.
Save anonymous/b7b6d6752aabdd1f9b59 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/playground');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
console.log('Connected to db');
});
var userSchema = new Schema({
email: String,
displayName: String,
subscriptions: [{
show: {type: Schema.Types.ObjectId, ref: 'Show'},
favorite: {type: Boolean, default: false}
}]
});
var showSchema = new Schema({
title: String,
overview: String,
subscribers: [{type: Schema.Types.ObjectId, ref: 'User'}],
episodes: [{
title: String,
firstAired: Date
}]
});
var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);
//create initial user and show
var user = new User({
email: "test@test.com",
displayName: "bill"
});
user.save(function(err, user) {
if (err) {
console.log(err);
}
var show = new Show({
title: "Some Show",
overview: "A show about some stuff."
});
show.save();
user.subscriptions.push(show);
user.save();
});
// try to find and poplate that user
User.findOne({
displayName: 'bill'
})
.populate('subscriptions.show')
.exec(function(err, user) {
if (err) {
console.log(err);
}
console.log(user);
/* results in:
{ _id: 53a7a39d878a965c4de0b7f2,
email: 'test@test.com',
displayName: 'bill',
__v: 1,
subscriptions: [ { _id: 53a7a39d878a965c4de0b7f3, favorite: false } ] }*/
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment