1
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!

3
  • Can you give some actual data please? Commented Feb 1, 2017 at 8:58
  • Updated question. Commented Feb 1, 2017 at 15:41
  • I have added an answer. This might fix your problem. Commented Feb 1, 2017 at 16:00

2 Answers 2

2

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);
    });
Sign up to request clarification or add additional context in comments.

8 Comments

I will double check, but I do believe I've tried that too, and it did not work.
@linxtion What is in your "data" when using my solution?
I get a { [CastError: Cast to ObjectId failed for value "{ stuff: 'SkpTCgxug' }" at path "_id"]
If I remove the extra wrapping array, and use populate('container.stuff') it works.
I'm probably just gonna go with using a single array, and manipulate the structure later.
|
0

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);
            });
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.