Created
December 27, 2015 00:42
-
-
Save futurist/f3815f2989e51dc03810 to your computer and use it in GitHub Desktop.
Mongoose populate an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'), | |
Schema = mongoose.Schema, | |
ObjectId = Schema.ObjectId; | |
mongoose.connect('mongodb://localhost/testy2'); | |
var UserSchema = new Schema({ | |
name: String | |
}); | |
var MovieSchema = new Schema({ | |
title: String, | |
tags: [new Schema({ | |
_name: {type: Schema.ObjectId, ref: 'Tag'}, | |
_owner: {type: Schema.ObjectId, ref: 'User'} | |
})] | |
}); | |
var TagSchema = new Schema({ | |
name: String | |
}); | |
var Tag = mongoose.model('Tag', TagSchema), | |
User = mongoose.model('User', UserSchema), | |
Movie = mongoose.model('Movie', MovieSchema); | |
User.create({name: 'Johnny'}, function(err, johnny) { | |
Tag.create({name: 'drama'}, function(err, drama) { | |
Movie.create({'title': 'Dracula', tags:[{_name: drama._id, _owner: johnny._id}]}, function(err, movie) { | |
Movie.findById(movie).populate('tags._owner').run(function(err, movie) { | |
console.log(movie.tags[0]._owner); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment