Search code examples
apireststrapi

Strapi: how to create a new model that belongs to a user?


I'm just getting started with Strapi.io and I'm currently working on a dummy project to test it out. Note that since I'm using the UI, I don't have any code to share, but I'll try to be as explicit as I can to describe what I want and what I've tried.

I have created a "todo" collection type that has a title, description, category and a user associated with it. The user is a relationship (one user has many todos) to the default user entity created with the Strapi app. When I run http POST http://localhost:1337/todos "Authorization: Bearer <TOKEN>" title="title" description="description" category="category" (I'm doing it with Postman) it works, but I see that the user field is null. I would like it to be automatically assigned based on the user who posted this command. Is that possible to achieve?

Many thanks!

enter image description here


Solution

  • Yes, it's absolutely possible. The way you do this is, you first identify which user actually made this request. This can be done by accessing the ctx.state.user variable. This is a global variable set by Koa so you can access this in the controller. Now to save the relationship of user against the todo collection entry you only need to pass the user id of the user calling this api. This can be retrieved by using ctx.state.user.id. So you can use the code below to create a todo collection correctly:

    Sample code:
    await strapi.services.todo.create({
       title: 'My Todo Title',
       description: 'My Description here',
       category: 'Work',
       user: ctx.state.user.id
    })
    

    P.S: You need to make sure you're logged in and are using a bearer token while calling the api or else, ctx.state.user will be null.