How to Reference and Populate Object Embedded in Another Collection

Here’s my Claim Schema:

var Claims = mongoose.Schema({

   billed_insurances:
   [
       {type: mongoose.Schema.Types.ObjectId, ref: 'Insurances'},
   ]
});

module.exports = mongoose.model("Claims", Claims);

Here’s my Patient Schema

var Patients = mongoose.Schema({
   name: 
   {
       first_name: {type: String, required: true}, 
       last_name: {type: String, required: true}
   },
   insurances: 
   [
       carrier: {type: mongoose.Schema.Types.ObjectId, ref: 'Carriers', required: true},
       member_id: {type: String, required: true},
   ]
});

module.exports = mongoose.model("Patients", Patients);

I’m trying to store and populate a reference from ‘insurances’ in Patient to billed_insurances in Claims. Storing it is no problem, but I haven’t been able to successfully populate the billed_insurances array.

Here’s my populate call:

Claim.findOne({_id : claimId}).populate({path: 'billed_insurances'})

When I run this, billed_insurances comes back as an empty array. I’d like to keep insurances embedded within the Patient and not extrapolated to it’s own collection since it’s always accessed when other Patient info is accessed. I’ve tried making insurances it’s own subdocument, among other things, however still no luck. How should I accomplish this?

Hi @macintosh1097, welcome to the community.
I created a sample to populate an array of ObjectIDs using mongoose and it seems to work as expected.
The following query:

  const popluatedClaim = await Claim.findById(insertedClaim._id).populate({
    path: "billed_insurances",
  });

returned the following populated document.

  {
    _id: new ObjectId("62bbe0968c7777b4c0ce0db8"),
    billed_insurances: [
      { _id: new ObjectId("62bbe0968c7777b4c0ce0db2"), name: 'Lorem', __v: 0},
      { _id: new ObjectId("62bbe0968c7777b4c0ce0db3"), name: 'Ipsum', __v: 0},
      { _id: new ObjectId("62bbe0968c7777b4c0ce0db4"), name: 'Dolor', __v: 0},
      { _id: new ObjectId("62bbe0968c7777b4c0ce0db5"), name: 'Sit', __v: 0 }
    ],
    __v: 0
  }

Please take a look at this gist to learn more:

Please note that the naming convention I followed was as per the mongoose documentation:

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database.

Hence I used the model names as Insurance & Claim instead of their plural forms.

The version of mongoose that I am using is ^6.4.1 and it worked perfectly fine. Please let me know in case you are using a different version of mongoose and the array is not getting populated using .populate method as shown above.

If you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
MongoDB

2 Likes