Raw
1 ---
2 sidebar_label: "findAndCount"
3 ---
4
5 import { TypeList } from "docs-ui"
6
7 export const metadata = {
8 title: `findAndCount Method - Data Model Repository Reference`,
9 }
10
11 # {metadata.title}
12
13 The `findAndCount` method of a data model repository retrieves a list of records and the total count of records that match the query.
14
15 <Note>
16
17 This reference assumes you've already resolved the data model repository, as explained in the [Data Model Repository Reference](../../page.mdx) documentation.
18
19 </Note>
20
21 ## `findAndCount` Parameters
22
23 <TypeList
24 types={[
25 {
26 type: "`object`",
27 name: "data",
28 description: "Options to filter and configure the query to retrieve the records.",
29 required: false,
30 children: [
31 {
32 type: "`object`",
33 name: "where",
34 description: "Filters to apply to the query. The keys are the property names of the data model, and the values are the values to filter by.",
35 required: false,
36 },
37 {
38 type: "`object`",
39 name: "options",
40 description: "Options to configure the query.",
41 required: false,
42 children: [
43 {
44 type: "`string[]`",
45 name: "populate",
46 description: "An array of relation names to retrieve.",
47 required: false,
48 },
49 {
50 type: "`string[]`",
51 name: "fields",
52 description: "An array of property names to retrieve.",
53 required: false,
54 },
55 {
56 type: "`number`",
57 name: "limit",
58 description: "The number of records to retrieve.",
59 required: false,
60 defaultValue: "`15`",
61 },
62 {
63 type: "`number`",
64 name: "offset",
65 description: "The number of records to skip before the retrieved records.",
66 required: false,
67 defaultValue: "`0`",
68 },
69 {
70 type: "`object`",
71 name: "orderBy",
72 description: "An object whose keys are the property names of the data model, and values are the sorting order.",
73 required: false,
74 },
75 {
76 type: "`string | string[]`",
77 name: "groupBy",
78 description: "Group the records by one or more properties.",
79 required: false,
80 },
81 {
82 type: "`select-in` \\| `joined`",
83 name: "strategy",
84 description: "The strategy to use to retrieve the records. Learn more in the [MikroORM documentation](https://mikro-orm.io/docs/loading-strategies). If you don't specify a strategy and you specify the `limit` or `offset` options, the default strategy is `select-in`. Otherwise, the default strategy is `joined`.",
85 required: false,
86 }
87 ]
88 }
89 ]
90 }
91 ]}
92 sectionTitle="findAndCount Parameters"
93 openedLevel={1}
94 />
95
96 ---
97
98 ## Retrieve List of Records
99
100 To retrieve a list of records matching a set of filters, use the `findAndCount` method of the data model repository:
101
102 <Note>
103
104 As of [Medusa v2.11.0](https://github.com/medusajs/medusa/releases/tag/v2.11.0), MikroORM dependencies are included in the `@medusajs/framework` package. If you're using an older version of Medusa, change the import statement to `@mikro-orm/knex`.
105
106 </Note>
107
108 ```ts title="src/modules/blog/service.ts"
109 import {
110 InjectTransactionManager,
111 MedusaContext,
112 MedusaService,
113 InjectManager,
114 } from "@medusajs/framework/utils"
115 import { Context, InferTypeOf, DAL } from "@medusajs/framework/types"
116 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
117 import Post from "./models/post"
118
119 class BlogModuleService extends MedusaService({
120 Post,
121 }){
122 // ...
123 @InjectTransactionManager()
124 protected async doSomething_(
125 id: string,
126 @MedusaContext() sharedContext?: Context<EntityManager>
127 ): Promise<any> {
128 const [posts, count] = await this.postRepository_.findAndCount()
129
130 return {
131 posts,
132 count,
133 }
134 }
135
136 @InjectManager()
137 async doSomething(
138 id: string,
139 @MedusaContext() sharedContext?: Context<EntityManager>
140 ): Promise<any> {
141 return await this.doSomething_(id, sharedContext)
142 }
143 }
144 ```
145
146 ### Returns
147
148 The method returns a tuple of two elements:
149
150 - An array of the first `15` records of the data model.
151 - The total count of records that match the query.
152
153 ---
154
155 ## Filter Records
156
157 You can filter the retrieved records by passing filters as a first parameter of the `findAndCount` method:
158
159 ```ts title="src/modules/blog/service.ts"
160 import {
161 InjectTransactionManager,
162 MedusaContext,
163 MedusaService,
164 InjectManager,
165 } from "@medusajs/framework/utils"
166 import { Context, InferTypeOf, DAL } from "@medusajs/framework/types"
167 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
168 import Post from "./models/post"
169
170 class BlogModuleService extends MedusaService({
171 Post,
172 }){
173 // ...
174 @InjectTransactionManager()
175 protected async doSomething_(
176 id: string[],
177 @MedusaContext() sharedContext?: Context<EntityManager>
178 ): Promise<any> {
179 const [posts, count] = await this.postRepository_.findAndCount({
180 where: {
181 id,
182 },
183 })
184
185 return {
186 posts,
187 count,
188 }
189 }
190
191 @InjectManager()
192 async doSomething(
193 id: string,
194 @MedusaContext() sharedContext?: Context<EntityManager>
195 ): Promise<any> {
196 return await this.doSomething_(id, sharedContext)
197 }
198 }
199 ```
200
201 ### Parameters
202
203 The first object parameter is an object that has a `where` property used to apply filters. `where`'s value is an object whose keys are the property names of the data model, and values are the values to filter by.
204
205 In the example above, you filter the retrieved posts by their `id` property.
206
207 <Note>
208
209 Refer to the [Filtering](../../tips/filtering/page.mdx) reference for more information on how to filter records.
210
211 </Note>
212
213 ### Returns
214
215 The method returns a tuple of two elements:
216
217 - An array of the first `15` records matching the filters.
218 - The total count of records that match the query.
219
220 ---
221
222 ## Retrieve Relations
223
224 <Note>
225
226 This applies to relations between data models of the same module. To retrieve linked records of different modules, use [Query](!docs!/learn/fundamentals/query).
227
228 </Note>
229
230 ```ts title="src/modules/blog/service.ts"
231 import {
232 InjectTransactionManager,
233 MedusaContext,
234 MedusaService,
235 InjectManager,
236 } from "@medusajs/framework/utils"
237 import { Context, InferTypeOf, DAL } from "@medusajs/framework/types"
238 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
239 import Post from "./models/post"
240
241 class BlogModuleService extends MedusaService({
242 Post,
243 }){
244 // ...
245 @InjectTransactionManager()
246 protected async doSomething_(
247 id: string[],
248 @MedusaContext() sharedContext?: Context<EntityManager>
249 ): Promise<any> {
250 const [posts, count] = await this.postRepository_.findAndCount({
251 where: {
252 id,
253 },
254 options: {
255 populate: ["author"],
256 },
257 })
258
259 return {
260 posts,
261 count,
262 }
263 }
264
265 @InjectManager()
266 async doSomething(
267 id: string,
268 @MedusaContext() sharedContext?: Context<EntityManager>
269 ): Promise<any> {
270 return await this.doSomething_(id, sharedContext)
271 }
272 }
273 ```
274
275 ### Parameters
276
277 The first object parameter of `findAndCount` accepts an `options` property, whose value is an object of retrieval options.
278
279 It accepts a `populate` property, whose value is an array of relation names to retrieve.
280
281 In the example above, you retrieve the `author` relation of the posts.
282
283 ### Returns
284
285 The method returns a tuple of two elements:
286
287 - An array of the first `15` records.
288 - The total count of records that match the query.
289
290 Each record in the array will have the specified relations populated:
291
292 ```json title="Example"
293 [
294 {
295 "id": "1",
296 "author": {
297 "id": "1",
298 "name": "John Doe",
299 // ...
300 },
301 // ...
302 }
303 ]
304 ```
305
306
307 ---
308
309 ## Select Properties
310
311 ```ts title="src/modules/blog/service.ts"
312 import {
313 InjectTransactionManager,
314 MedusaContext,
315 MedusaService,
316 InjectManager,
317 } from "@medusajs/framework/utils"
318 import { Context, InferTypeOf, DAL } from "@medusajs/framework/types"
319 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
320 import Post from "./models/post"
321
322 class BlogModuleService extends MedusaService({
323 Post,
324 }){
325 // ...
326 @InjectTransactionManager()
327 protected async doSomething_(
328 id: string,
329 @MedusaContext() sharedContext?: Context<EntityManager>
330 ): Promise<any> {
331 const [posts, count] = await this.postRepository_.findAndCount({
332 where: {
333 id,
334 },
335 options: {
336 fields: ["title"],
337 },
338 })
339
340 return {
341 posts,
342 count,
343 }
344 }
345
346 @InjectManager()
347 async doSomething(
348 id: string,
349 @MedusaContext() sharedContext?: Context<EntityManager>
350 ): Promise<any> {
351 return await this.doSomething_(id, sharedContext)
352 }
353 }
354 ```
355
356 ### Parameters
357
358 By default, retrieved records have all their properties. The first object parameter of `findAndCount` accepts in its `options` property a `fields` property, whose value is an array of property names to retrieve.
359
360 In the example above, you retrieve only the `title` property of the posts.
361
362 ### Returns
363
364 The method returns a tuple of two elements:
365
366 - An array of the first `15` records.
367 - The total count of records that match the query.
368
369 Each record in the array will have only the specified properties:
370
371 ```json title="Example"
372 [
373 {
374 "id": "1",
375 "title": "My first post"
376 }
377 ]
378 ```
379
380 ---
381
382 ## Paginate Relations
383
384 ```ts title="src/modules/blog/service.ts"
385 import {
386 InjectTransactionManager,
387 MedusaContext,
388 MedusaService,
389 InjectManager,
390 } from "@medusajs/framework/utils"
391 import { Context, InferTypeOf, DAL } from "@medusajs/framework/types"
392 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
393 import Post from "./models/post"
394
395 class BlogModuleService extends MedusaService({
396 Post,
397 }){
398 // ...
399 @InjectTransactionManager()
400 protected async doSomething_(
401 id: string,
402 @MedusaContext() sharedContext?: Context<EntityManager>
403 ): Promise<any> {
404 const [posts, count] = await this.postRepository_.findAndCount({
405 where: {
406 id,
407 },
408 options: {
409 limit: 10,
410 offset: 10,
411 },
412 })
413
414 return posts
415 }
416
417 @InjectManager()
418 async doSomething(
419 id: string,
420 @MedusaContext() sharedContext?: Context<EntityManager>
421 ): Promise<any> {
422 return await this.doSomething_(id, sharedContext)
423 }
424 }
425 ```
426
427 ### Parameters
428
429 By default, the `find` method retrieves the first `15` records.
430
431 To change pagination configurations, you can pass to the first object parameter the `options` property, whose value is an object that accepts the following properties for pagination:
432
433 - `limit`: a number indicating how many records to retrieve. By default, it's `15`.
434 - `offset`: a number indicating how many records to skip before the retrieved records. By default, it's `0`.
435
436 In the example above, you retrieve `10` records, skipping the first `10` records.
437
438 ### Returns
439
440 The method returns an array of records. The number of records is less than or equal to `limit`'s value.
441
442 ---
443
444 ## Sort Records
445
446 ```ts title="src/modules/blog/service.ts"
447 import {
448 InjectTransactionManager,
449 MedusaContext,
450 MedusaService,
451 InjectManager,
452 } from "@medusajs/framework/utils"
453 import { Context, InferTypeOf, DAL } from "@medusajs/framework/types"
454 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
455 import Post from "./models/post"
456
457 class BlogModuleService extends MedusaService({
458 Post,
459 }){
460 // ...
461 @InjectTransactionManager()
462 protected async doSomething_(
463 id: string,
464 @MedusaContext() sharedContext?: Context<EntityManager>
465 ): Promise<any> {
466 const [posts, count] = await this.postRepository_.findAndCount({
467 where: {
468 id,
469 },
470 options: {
471 orderBy: {
472 title: "ASC",
473 },
474 },
475 })
476
477 return {
478 posts,
479 count,
480 }
481 }
482
483 @InjectManager()
484 async doSomething(
485 id: string,
486 @MedusaContext() sharedContext?: Context<EntityManager>
487 ): Promise<any> {
488 return await this.doSomething_(id, sharedContext)
489 }
490 }
491 ```
492
493 ### Parameters
494
495 To sort records by one or more properties, the first object parameter of `findAndCount` accepts in its `options` property an `orderBy` property. Its value is an object whose keys are the property names of the data model, and values are the sorting order.
496
497 The sorting order can be one of the following:
498
499 - `ASC` to sort by this property in the ascending order.
500 - `DESC` to sort by this property in the descending order.
501
502 ### Returns
503
504 The method returns a tuple of two elements:
505
506 - An array of the first `15` records.
507 - The total count of records that match the query.