Kaherdin
Kaherdin

Reputation: 2127

Strapi : populate result from a relation collection

I'm using strapi 3.4.4 with mongodb. I've got a location collection with a reservation linked collection (a location can have many reservations).

Location Model

Reservations Model

My goal is to populate the author name when I made a get request to /location But right now, my request is :

{
"reservations": [
   {
   "_id": "60be41626a15ab675c91f417",    
   "author": "60be3d40ea289028ccbd4d5a",
   "id": "60be41626a15ab675c91f417"
   }
],
"_id": "60be40a26a15ab675c91f414",
"title": "New York Plaza",
},

As you can see, the author is an id, so I try to edit location/controllers/location.js to

const { sanitizeEntity } = require('strapi-utils');

module.exports = {
  /**
   * Retrieve records.
   *
   * @return {Array}
   */

  async find(ctx) {
    let entities;
    if (ctx.query._q) {
      entities = await strapi.services.location.search(ctx.query);
    } else {
      entities = await strapi.services.location.find(ctx.query, ['reservations', 'reservations.author']);
    }

    return entities.map(entity => sanitizeEntity(entity, { model: strapi.models.location }));
  },
};

I followed this guide : https://www.youtube.com/watch?v=VBNjCgUokLk&list=PL7Q0DQYATmvhlHxHqfKHsr-zFls2mIVTi&index=27

Upvotes: 0

Views: 5380

Answers (2)

I. Murtagh
I. Murtagh

Reputation: 11

You need to provide the API key you're using "Full access" for what ever reason, "Read only" won't return relations.

On top of that you will still need to use the query parameter populate.

http://localhost:1337/api/locations?populate=* 

Upvotes: 1

Kaherdin
Kaherdin

Reputation: 2127

After further research, it seems that the syntax ['reservations', 'reservations.author'] doesn't work to populate with mongodb.

await strapi.services.post.find(ctx.query, {path:'reservations', populate:{path:'author'}});

works

Upvotes: 1

Related Questions