2
First = new mongoose.Schema({
  name: String,
  second: {type: Schema.Types.ObjectId, ref: 'Second'},
});

Second = new mongoose.Schema({
  name: String,
  third: {type: Schema.Types.ObjectId, ref: 'Third'},
});


Third = new mongoose.Schema({
  name: String
});

First.find({}).populate({
  path: 'Second',
  populate: { path:  'Third'}
  }).exec(function(err, result) {
    console.log(result)
    })

First populate is ok, but Third is always null. Meaning I got some thing like this:

{
  name: 1,
  second: {
    name: 2,
    third: null

    }}
Sato
  • 8,192
  • 17
  • 60
  • 115

1 Answers1

1
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/test');

var FirstSchema = new mongoose.Schema({
  name: String,
  second: {type: Schema.Types.ObjectId, ref: 'Second'},
});

var SecondSchema = new mongoose.Schema({
  name: String,
  third: {type: Schema.Types.ObjectId, ref: 'Third'},
});


var ThirdSchema = new mongoose.Schema({
  name: String
});

var First = mongoose.model('First', FirstSchema);
var Second = mongoose.model('Second', SecondSchema);
var Third = mongoose.model('Third', ThirdSchema);

First.remove({}).exec();
Second.remove({}).exec();
Third.remove({}).exec();

var _3 = new Third({name: 'third'});
_3.save(function(err1) {
  if (err1) {
    throw err1;
  }
  var _2 = new Second({name: 'second', third: _3.id});
  _2.save(function(err2) {
    if (err2) {
      throw err2;
    }
    var _1 = new First({name: 'first', second: _2.id});

    _1.save(function() {
      First.find({}).populate({
        path: 'second',
        populate: { path:  'third'}
      }).exec(function(err, result) {
        console.log(result[0]);
      });
    });
  });
});

enter image description here

is there your path is assigned by a wrong value or something?

it should be a field name, not a object name

Ethan Wu
  • 87
  • 6
  • forgive the callback hell – Ethan Wu Mar 18 '16 at 03:06
  • Those `.remove()` calls are a problem since you are not waiting for the callback to complete. Which means chances are this would wipe the data before you queried it. The general principle is correct *"field name not **model** name"* for path. Would also be nice if you just posted the text output rather than a screenshot. – Blakes Seven Mar 18 '16 at 03:13