Strapi Cron任务无法获取用户列表:find方法报错求解决方案
Strapi Cron任务获取用户列表报错解决方案
问题分析
你遇到的strapi.service(...).find is not a function错误,核心原因是用户服务的find方法调用不符合Strapi v4的规范,或是参数缺失导致方法无法正常识别。
修改方案
方案1:修正服务find方法的调用参数
Strapi v4中,用户权限插件的用户服务find方法必须接收一个包含查询配置的对象参数(即使是空对象),修改cron-tasks.js代码如下:
module.exports = { '*/5 * * * * *': async ({ strapi }) => { try { // 传入空对象参数,可选添加populate获取关联字段 const users = await strapi.service("plugin::users-permissions.user").find({}); console.log(users); } catch (error) { console.log(error); } }, };
方案2:使用数据库查询API(更稳定推荐)
如果服务调用仍有问题,建议直接使用Strapi的数据库查询API,兼容性更强:
module.exports = { '*/5 * * * * *': async ({ strapi }) => { try { // 使用db.query的findMany方法查询用户 const users = await strapi.db.query('plugin::users-permissions.user').findMany({ // 可选:添加populate获取关联字段,比如用户角色 // populate: ['role'] }); console.log(users); } catch (error) { console.log(error); } }, };
额外注意
检查cron-tasks.js文件语法,你提供的代码末尾多了一个多余的};,需要删除以保证语法正确。
内容的提问来源于stack exchange,提问作者SnNaCk
相关产品推荐
相关产品推荐

