Search code examples
mongodbmongoosemongoose-populate

Populate nested ObjectId


My profile document is saved in my DB as the following:

{
    "_id": {
        "$oid": "5c3aa1de18ad682fb1444138"
    },
    "user": {
        "$oid": "5c318f56e3224b15e0fdbd06"
    },
    "company": {
        "info": {
            "$oid": "5c318f56e3224b15e0fdbd07"
        },
        "position": "Stemuli"
    },
    "hometown": "Dallas",
    "date": {
        "$date": "2019-01-13T02:26:38.185Z"
    },
    "__v": 0
}

I am trying to populate the field company.info within the newly saved Profile.

new Profile(profileFields).save().then(profile => {
          Profile.populate(profile, { path: "company.info" }, (err, p) => {
            console.log(err);
            console.log(p);
          });
        });

I get the following returned for the company field

company: {id: "5c318f56e3224b15e0fdbd07", position: "Stemuli"}

And the document that this id is linked to is the following:

{
    "_id": {
        "$oid": "5c318f56e3224b15e0fdbd07"
    },
    "employees": [
        {
            "$oid": "5c318f56e3224b15e0fdbd06"
        }
    ],
    "name": "Company",
    "__v": 14
}

How can I get it to populate the actual company document instead of just the id?

Profile Schema

// Create Schema
const ProfileSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "users"
  },
  company: {
    id: { type: Schema.Types.ObjectId, ref: "industrypartners" },
    position: { type: String }
  },
  work_experience: Array,
  hometown: { type: String },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = Profile = mongoose.model("profile", ProfileSchema);

Industry Partner Schema

// Create Schema
const IndustryPartnerSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  schools: [{ type: Schema.Types.ObjectId, ref: "schools" }]
});

module.exports = IndustryPartner = mongoose.model(
  "industrypartner",
  IndustryPartnerSchema
);

Solution

  • Try with this:

    new Profile(profileFields).save().then(profile => {
      Profile.populate(Profile, { 
        path: "company.info",
        select: {
          _id: 1,
          employees: 1,
          name: 1,
        }
      }, (err, p) => {
        console.log(err);
        console.log(p);
      });
    });