Query models inside a lifecycle hook

System Information
  • Strapi Version: 4.0.0
  • Operating System: Windows 10
  • Database: SQL lite
  • Node Version: 14.16.1
  • NPM Version: 6.14.12
  • Yarn Version: 1.22.10

Hello,

I have a model that contains a relation to a User-permissions.
Typically a Post with its related Author.

I’d like to add a computed data to my post : the Author name, in addition of the already stored ID of the related author.
I’m trying to get this value in a “beforeUpdate” hook for now.
I can get the ID of the related author, and so I have to query this specific user to retrieve his name.

I have something like this, where data.author is the ID of the user

module.exports = {
  async beforeUpdate(event) {
    const { data, where, select, populate } = event.params;
    if (data.author) {
      const res = await strapi.query("user", "users-permissions").findOne({ id: data.author})
      // ... get the user name and store it
    }
  }
}

But I get an error on this query, “error: Model user not found”
I’ve tried with my other models, but no query succeeds, I always get the same error.

Does anyone ever implemented something like that and succeeded ?
Any help will be appreciated !

Thanks for reading me, have a nice day

So, that wordked for me :

const res = await strapi.service("plugin::users-permissions.user").fetch({ id: data.author})

I’m not sure why I have to query the service here and not the model, but that works !

1 Like