public
Created

populating a referenced mongoose model, three levels deep

  • Download Gist
main.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
var mongoose = require('mongoose'),
assert = require('assert')
 
mongoose.connect('localhost/mydb');
 
var Schema = mongoose.Schema;
 
var ContainerSchema = new Schema({
name: String,
})
 
var MasterSchema = new Schema({
name: String,
container: [{type: Schema.Types.ObjectId, ref: 'Container'}]
});
 
var PanelSchema = new Schema({
name: String,
master: [MasterSchema]
});
 
var AppSchema = new Schema({
name: String,
panel: [PanelSchema]
});
 
var App = mongoose.model('App', AppSchema);
var Panel = mongoose.model('Panel', PanelSchema);
var Master = mongoose.model('Master', MasterSchema);
var Container = mongoose.model('Container', ContainerSchema);
 
var container = new Container({name:'page'});
container.save(function(err) {
var master = new Master({name:'meester'});
master.container.push(container);
master.save(function(err) {
var panel = new Panel({name:'paneel'});
panel.master.push(master);
panel.save(function(err) {
var app = new App({name:'application'});
app.panel.push(panel);
app.save(function(err) {
App.findOne({name:'application'})
.populate('panel.master.container')
.exec(function(err, prog) {
if (err) throw new Error('not found');
assert.equal(prog.panel[0].name, 'paneel');
assert.equal(prog.panel[0].master[0].name, 'meester');
assert.equal(prog.panel[0].master[0].container[0].name, 'page'); // <== fails
process.exit();
});
});
});
});
});
prog.panel[0].master[0].container

contains the id, thus [ 50923746587365835 ]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.