Home > Back-end >  Mongoose won't populate inside array
Mongoose won't populate inside array

Time:11-14

So, I have this project model that has an owner, which can be either a User or a Team

const projectSchema = new Schema<IProject>({
    projectName: { 
        type: String, 
        required: true 
    },
    description: {
        type: String,
        required: false
    },
    site: { 
        type: String, 
        required: false
    },
    owner: { 
        type: Schema.Types.ObjectId, 
        required: true,
        refPath: 'ownerModel'
    },
    ownerModel: {
        type: String,
        required: true,
        enum: ['Team', 'User']
    },
    slug: { 
        type: String, 
        required: true,
        unique: true,
        dropDups: true 
    },
    keywords: { 
        type: [String], 
        required: true 
    }
})

The problem I'm having is when the owner is a team, because teams can have multiple owners, like this

const teamSchema = new Schema<ITeam>({
  teamName: { 
    type: String, 
    required: true
  },
  owner: { 
    type: [Schema.Types.ObjectId], 
    required: true,
    ref: 'User' 
  },
  slug: { 
    type: String, 
    required: true,
    unique: true
  },
  bio: { 
    type: String, 
    required: false 
  },
  verified: { 
    type: Boolean, 
    required: true,
    default: false 
  },
  quote: { 
    type: String, 
    required:false
  },
  members: [{ 
    member: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true
    },
    status: {
      type: String,
      required: true,
      enum: ["accepted", "pending"]
    },
    type: {
      type: String,
      required: true,
      enum: ["admin", "coworker"]
    }
  }],
  followers: { 
    type: Number, 
    required: true 
  },
  logo: { 
    type: String, 
    required: false 
  },
  type: { 
    type: String, 
    required: true 
  },
})

And while I got to populate the owner field of the project (aka loading the team), I can't for the life of me make the owner of the team neither the members of it load via populate.

I tried owner.owner, tried altering the model to not use an array, tried using deepPopulate plugin but got a type error. Nothing worked

CodePudding user response:

I discovered how to do it, all I had to do was use the mongoose object properly, don't know how I let this past me. Here's it

let projetos = await ProjectModel.find({owner: args.id, ownerModel: "Team"})
      .populate({ path: 'owner', 
                  populate: [
                    {
                      path: 'owner'
                    }, 
                    {
                      path: 'members'
                    }
                  ]
                });

I used an array as I wanted to populate more than one field. Mongoose doc on this

  • Related