Mongoose populate with array of objects containing ref

neverfox picture neverfox · May 20, 2013 · Viewed 82.2k times · Source

I have a Mongoose schema with an array lists of objects that consist of a reference to another collection and a nested array of numbers:

var Schema, exports, mongoose, schema;

mongoose = require("mongoose");

Schema = mongoose.Schema;

schema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  lists: [
    {
      list: {
        type: Schema.ObjectId,
        require: true,
        ref: "List"
      },
      allocations: [
        {
          type: Number,
          required: true
        }
      ]
    }
  ],
  createdAt: {
    type: Date,
    "default": Date.now
  },
  updatedAt: {
    type: Date
  }
});

exports = module.exports = mongoose.model("Portfolio", schema);

However, I cannot get populate to work as expected without getting a TypeError: Cannot read property 'ref' of undefined. I've tried populate('list') and populate('lists list') but I'm either not calling things correctly or my Schema isn't formed correctly. I don't have this problem if I simply reference the lists by themselves:

lists: [
    {
        type: Schema.ObjectId,
        require: true,
        ref: "List"
    }
  ]

but I want to have the allocations array alongside each list. What do I need to do to get the behavior I want?

Answer

neverfox picture neverfox · May 20, 2013

I found the answer: populate('lists.list') works. Thanks to this question: Mongoose populate within an object?