scottwrobinson / camo

A class-based ES6 ODM for Mongo-like databases.
556 stars 80 forks source link

Populating Documents within an array of Document within a Document 😅 #91

Closed SteffanDonal closed 7 years ago

SteffanDonal commented 7 years ago

I'm loving Camo so far, very clean and concise for what I need it for.

However I'm running into an issue where I'm loading a Document that contains an array of Documents, each of which has a single reference to another Document.
For example: Playlist > QueuedSongs[] > Song

Currently when I retrieve the Playlist I then need to do a playlist.queuedSongs.forEach(qSong => qSong.populate()); which isn't ideal as it produces more cruft.

Is there a method to do this that I'm missing?

scottwrobinson commented 7 years ago

Sorry for not getting back to you sooner.

No, unfortunately this is not possible at the moment. Camo can't load arbitrarily deep references for you. It is, however, on the list of features for the 2.0 release. Until then you'll have to manually load (populate()) the references.

Let me know if you need anything else, otherwise feel free to close the issue. Thanks!

SteffanDonal commented 7 years ago
populate() {
        var chain = Promise.resolve();

        if (this.requests.length > 0 && typeof this.requests[0] === 'string') {
            chain = chain.then(() => super.populate());
        }

        return chain
            .then(() => Promise.all(this.requests.map(request => request.populate())))
            .then(() => this);
    }

This is roughly what I ended up doing - this is an instance method defined on the Playlist. It'll populate the list of requests, then for each one it'll populate the data inside that request.