Created
November 20, 2015 03:38
-
-
Save apache2046/9cc611f91636712694e4 to your computer and use it in GitHub Desktop.
Mongoose populate an array
This file contains 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