Strapi.service(...).find() return same data

System Information
  • Strapi Version: 4.0.6
  • Operating System: Win10
  • Database: “sqlite3”: “5.0.2”
  • Node Version: v12.19.0
  • NPM Version: 6.14.8

I’m writing custom controller and want to get filtered data from another collection by this code

const result = await strapi.service('api::bookshelf.bookshelf').find({user_id: id});

but I always get same data here no matter what id like this

user_bookshelf =  {
  results: [
    {
      id: 2,
      user_id: '1',
      createdAt: '2022-01-30T08:32:05.538Z',
      updatedAt: '2022-01-30T08:32:05.538Z'
    },
    {
      id: 3,
      user_id: '3',
      createdAt: '2022-01-30T09:32:16.553Z',
      updatedAt: '2022-01-30T09:32:16.553Z'
    }
  ],
  pagination: { page: 1, pageSize: 25, pageCount: 1, total: 2 }
}

.
.

I have use this in Strapi version 3.6.6

const entity = await strapi.services.bookshelf.findOne({ id });

but now it not working and got the error

error: Cannot read property ‘findOne’ of undefined

Hey, I think you have to use “where” and the db.query api. This should work:

const result = await strapi.db.query(‘api::bookshelf.bookshelf’).findOne({
where: {user: {id: id}},
});

You can find the docs on query engine api here: Query Engine API | Strapi Documentation

(Tbh I can agree that the difference between using the query engine api or the service api is not very clear, I faced the same issue).

2 Likes

omg It works now! thank you so much.

also thanks for the docs , I have seen the docs but can’t find this, that was my bad.

1 Like

After thinking a bit I thing it would be better to use the entity service api, so that you can have more control over your request if you need it (sort, start, limit…).
Something like this:

const result = await strapi.entityService.findOne(‘api::bookshelf.bookshelf’, {
where: {user: {id: id}},
})

Related docs: Entity Service API | Strapi Documentation
Glad I could help :slight_smile: