xiao
xiao

Reputation: 1758

How to use Mongoose to populate array of arrays?

var Stuff = new mongoose.Schema({
  name: String,
  expiration: Date,
  cost: Number
});

var Container = new mongoose.Schema({
  stuff: { type: String, ref: 'stuff' },
});

var ContainerWrapper = new mongoose.Schema({
  container: [[container]] // array of arrays
});

ContainerWrapper document

{
  container: [
    [
      {stuff: 'ID1'},
      {stuff: 'ID2'},
    ],
    [
      {stuff: 'ID3'},
      {stuff: 'ID4'},
      {stuff: 'ID5'},
    ]
  ]
}

How can I get the population of stuff? I've tried variations of the code below

ContainerWrapper.find({}).populate({path: 'container.stuff'})

But none seems to be working.

Any help is appreciated!

Upvotes: 1

Views: 1351

Answers (2)

Thomas Bormans
Thomas Bormans

Reputation: 5372

You cannot use a regular populate, you will need a deep-populate. Here is some documentation.

ContainerWrapperModel
    .find()
    .lean()
    .populate({
        path: 'container',
        model: 'Container', 
        populate: {
            path: 'stuff',
            model: 'Stuff'
        }
    })
    .exec(function(err, data) {
        console.log(data);
    });

Upvotes: 2

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11950

Try this example below, should work, if not, comment below

ContainerWrapper
    .find({})
    .exec(function(err, data) {

        // get container ids
        // convert [[1, 2],['a', 'b', 'c']] into [1, 2, 'a', 'b', 'c']
        var containers = data.container.reduce(function(arr, next) {
            next.forEach(function(containerItem) {
                arr.push(containerItem);
            });
            return arr;
        }, []);

        // population options, try playin with other fields
        var options = {path: 'stuff', model: 'Contanier'};

        Container
            .populate(containers, options)
            .exec(function(containerErr, containerData) {

                // populated containers
                console.log(containerData);
            });
    });

Upvotes: 0

Related Questions