API - Username instead of id on _by/_mby

My bad, I should have mentioned that populate only work with collectionLink.

And you can’t retrieve accountLink data with collection data at the same time. Maybe it could be the security reason.

Option 1

Fire one more API request with account ID to get the user data

Option 2

Ref answer by raffaelj: How to refer to another Collections or "Accounts" - #7 by raffaelj

  • create config directory in the root folder, under that directory create bootstrap.php file. Add the below codes. Make sure you don’t expose account sensitive data.

Replace “collection_name” with your actual collection name.

<?php

// This will append "author" object into API response. 

if (COCKPIT_API_REQUEST) {

    $app->on('collections.find.after.collection_name', function($name, &$entries) {


        function getSomeFields($array){
            $author_name = !empty($array['name'])?$array['name']:$array['user'];

            // Only return 2 fields "name" and "_id"
            return [
            "name" => $author_name,
            "_id"  => $array['_id']
           ];
        }

        foreach ($entries as &$entry) {

                $account         = $this->storage->findOne('cockpit/accounts', ['_id' => $entry['_by']]);
                $account         = !empty($account)?getSomeFields($account):[];

                // You can rename "author" as you want                
                $entry['author'] = $account;

        }

    });

}
2 Likes