sharkdawg
sharkdawg

Reputation: 984

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?

Upvotes: 1

Views: 2347

Answers (2)

sharkdawg
sharkdawg

Reputation: 984

Turns out it is just as simple as

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

Upvotes: 1

Neton Global
Neton Global

Reputation: 44

User Schema Here

 `let UserSchema = new Schema({
    email: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    profile: {
        firstName: {type: String,required: true},
        lastName: {type: String,required: true},
        address1: {type: String},
        address2: {type: String},
        city: {type: String},
        state: {type: String},
        zip: {type: String},
        phone: {type: String,required: true},
        avatar:{ type: Schema.Types.ObjectId, ref: 'Avatar'},
        shippingAddress:{
            address1: {type: String},
            address2: {type: String},
            city: {type: String},
            state: {type: String},
            zip: {type: String}
        },
    },
    redemptionCards : [{ type: Schema.Types.ObjectId, ref: 'CardCodes' }]
});`

Logic to get RedemptionCards:-

User.findOne({ email }).populate("redemptionCards")
            .exec(function (err, user) {
                CardData.populate(user.redemptionCards, {path: 'redemptionCards',match: { _id: { $ne: null }}}, function (err, cards) {
    console.log(cards);
});

FYI - CardData is the Hardcoded JSON file. Hope this helps.

Upvotes: 0

Related Questions