Get only some fields

System Information
  • Strapi Version:
  • Window:
  • MongoDB:
  • Node Version:
  • NPM Version:
  • Yarn Version:

I am creating a custom controller in Strapi, this is the code

controllers/user.js

'use strict';

module.exports = {
  async getUsername(ctx) {
    const { username } = ctx.params;
    const user = await strapi.query('user', 'users-permissions').findOne({ username });
    return user;
  }
};

routes.json

{
  "routes": [
    {
      "method": "GET",
      "path": "/user/:username",
      "handler": "user.getUsername",
      "config": {
        "policies": []
      }
    }
  ]
}

When making a GET request on ${API_URL}/user/${username} they return all user information, I just want to extract some fields. In mongo it would be something like this:db.colecctionUsers.findOne({ username }, { "name": 1, "username": 1, _id: 0}).

So I can get with mongo, only the username and the real name of the user minus the id, and it does not take the other fields. How can it be achieved with strapi?. Hope I can get help, I posted 2 previous threads and it seems this forum is dead.

Hello @Husdady , take a look at this page Here
I believe it will solve this question.

the problem is that when typing by console, strapi.services, it only returns 2 properties, the user or users property does not exist. If this is undefined, then it will return an error when trying to use the search or find method. Something like this gives an error:

strapi.services.user.find ({}) === bug

for now the solution I took was to return an obj with the properties I require. But it is not advisable to do that, the more data the user has, the more the response delay, I really want the server to return some data but it always returns everything

After making many attempts, I found a way to return specific fields from the user collection, this is the code:

'use strict';

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

module.exports = {
  async getUsername(ctx) {
    const { username } = ctx.params;
    const user = await strapi.query('user', 'users-permissions').findOne({ username });
    const entity = sanitizeEntity(user, {
      model: strapi.query('user', 'users-permissions').model,
      includeFields: ['username']
    });
    const userName = _.omit(entity, ['createdAt', 'updatedAt', '_id', 'id', '__v']);
    return userName;
  }
}

this way I can get only the username, thus avoiding getting all the user’s information, you should add this in the strapi documentation, maybe it can help

FYI this will be much easier in the v4 as we are adding native support for it, see this RFC: rfcs/xxxx-v4-rest-api.md at v4/rest-api · strapi/rfcs · GitHub

Specifically: rfcs/xxxx-v4-rest-api.md at v4/rest-api · strapi/rfcs · GitHub