Search code examples
node.jsmongodbmongoosemongoose-populate

Populate nested array with Mongoose


I have a user schema as shown below and I'm trying to populate the live projects array but I can't figure out how to access it.

const userSchema = new Schema({
  local: {
    email: String,
    username: String,
    password: String,
    liveProjects: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'liveProject'
    }]
  },
  google: {
    googleId: String,
    email: String,
    username: String,
    liveProjects: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'liveProject'
    }]
  }
});

const User = mongoose.model('user', userSchema);
module.exports = User;

If it wasn't embedded I could just use

User.findById(id).populate('liveProjects').exec((err,projects)=>{});

But how do I get access to 'local.liveProjects' or 'google.liveProjects' so that I can populate them?


Solution

  • Turns out it is just as simple as

    User.findById(id).populate('local.liveProjects').exec((err,projects)=>{});