Skip to content Skip to sidebar Skip to footer

Populate() Ref Nested In Object Array

I am trying to populate() all the subscriptions in my User model with data from the Show model. I have tried .populate('subscriptions.show') but it does nothing to the results. If

Solution 1:

Some code perhaps, also some corrections to your approach. You kind of want a "manyToMany" type of join which you can make as follows:

varasync = require("async"),
    mongoose = require("mongoose"),
    Schema = mongoose.Schema;


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


var userSchema = newSchema({
  email: String,
  displayName: String,
  subscriptions: [{ type: Schema.Types.ObjectId, ref: 'UserShow' }]
});

userShows = newSchema({
  show: { type: Schema.Types.ObjectId, Ref: 'Show' },
  favorite: { type: Boolean, default: false }
});

var showSchema = newSchema({
  title: String,
  overview: String,
  subscribers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  episodes: [{
    title: String,
    firstAired: Date
  }]
});


varUser = mongoose.model('User', userSchema);
varShow = mongoose.model('Show', showSchema);
varUserShow = mongoose.model('UserShow', userShows);

var user = newUser({
  email: 'test@test.com',
  displayName: 'bill'
});

user.save(function(err,user) {

  var show = newShow({
    title: "Some Show",
    overview: "A show about some stuff."
  });

  show.subscribers.push( user._id );
  show.save(function(err,show) {
    var userShow = newUserShow({ show: show._id });
    user.subscriptions.push( userShow._id );
    userShow.save(function(err,userShow) {
      user.save(function(err,user) {
        console.log( "done" );
        User.findOne({ displayName: "bill" })
          .populate("subscriptions").exec(function(err,user) {

          async.forEach(user.subscriptions,function(subscription,callback) {
              Show.populate(
                subscription,
                { path: "show" },
              function(err,output) {
                if (err) throw err;
                callback();
              });

          },function(err) {
            console.log( JSON.stringify( user, undefined, 4) );
          });


        });
      });
    });
  });

});

That should show a populated response much like this:

{"_id":"53a7b8e60462281231f2aa18","email":"test@test.com","displayName":"bill","__v":1,"subscriptions":[{"_id":"53a7b8e60462281231f2aa1a","show":{"_id":"53a7b8e60462281231f2aa19","title":"Some Show","overview":"A show about some stuff.","__v":0,"episodes":[],"subscribers":["53a7b8e60462281231f2aa18"]},"__v":0,"favorite":false}]}

Or without the "manyToMany" works also. Note here that there is no initial call to populate:

varasync = require("async"),
    mongoose = require("mongoose"),
    Schema = mongoose.Schema;


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


var userSchema = newSchema({
  email: String,
  displayName: String,
  subscriptions: [{
    show: {type: Schema.Types.ObjectId, ref: 'UserShow' },
    favorite: { type: Boolean, default: false }
  }]
});


var showSchema = newSchema({
  title: String,
  overview: String,
  subscribers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  episodes: [{
    title: String,
    firstAired: Date
  }]
});


varUser = mongoose.model('User', userSchema);
varShow = mongoose.model('Show', showSchema);

var user = newUser({
  email: 'test@test.com',
  displayName: 'bill'
});

user.save(function(err,user) {

  var show = newShow({
    title: "Some Show",
    overview: "A show about some stuff."
  });

  show.subscribers.push( user._id );
  show.save(function(err,show) {
    user.subscriptions.push({ show: show._id });
    user.save(function(err,user) {
        console.log( "done" );
        User.findOne({ displayName: "bill" }).exec(function(err,user) {

          async.forEach(user.subscriptions,function(subscription,callback) {
              Show.populate(
                subscription,
                { path: "show" },
              function(err,output) {
                if (err) throw err;
                callback();
              });

          },function(err) {
            console.log( JSON.stringify( user, undefined, 4) );
          });


        });
    });
  });

});

Solution 2:

check answer: https://stackoverflow.com/a/28180427/3327857

  Car   .find()   .populate({
    path: 'partIds',
    model: 'Part',
    populate: {
      path: 'otherIds',
      model: 'Other'
    }   
 })

Post a Comment for "Populate() Ref Nested In Object Array"