Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backend Aggregate Pipeline #10

Open
gdcho opened this issue May 9, 2023 · 4 comments
Open

Backend Aggregate Pipeline #10

gdcho opened this issue May 9, 2023 · 4 comments

Comments

@gdcho
Copy link
Member

gdcho commented May 9, 2023

Mongodb documentation

$sample - randomly selects "n" of documents from the database

{ $sample: { size: <positive integer N> } }

$lookup - performs an equality match on the localField to the foreignField from the documents of the from collection
$lookup syntax

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}
@gdcho
Copy link
Member Author

gdcho commented May 9, 2023

API route handler

const getMainThread = req.query.random
        ? getRandomMainThreads(parseInt(req.query.count) || 6)
        : getMainThreads();

If req query key is random (True), getRandomMainThreads, else (False), getMainTreads
When getRandomMainThreads, if query count is not given, default is 6

@gdcho
Copy link
Member Author

gdcho commented May 9, 2023

Postman GET URL: http://localhost:3000/api/threads/mainThread?random=True

{
"error": "Error: Could not find rootField queryRaw for action queryRaw for model undefined on rootType mutation"
}

@gdcho
Copy link
Member Author

gdcho commented May 9, 2023

Actually Prisma does not support the aggregation pipeline syntax directly.
We have to use Prisma's query builder.

Prisma query builder documentation - using cursor pagination

Key points:

  • take: limits the return count
  • cursor: the starting point of the query
  • Summary

@gdcho
Copy link
Member Author

gdcho commented May 9, 2023

{
    "error": "Error: \nInvalid `prisma.mainThread.findMany()` invocation:\n\n{\n  take: 6,\n  orderBy: [\n    {\n      id: 'asc'\n    }\n  ],\n  cursor: {\n    id: 0\n        ~\n  },\n  include: {\n    branchThread: true\n  }\n}\n\nArgument id: Got invalid value 0 on prisma.findManyMainThread. Provided Int, expected String.\n\n"
}

Get all the mainThread ids first

const entireIds = await prisma.mainThread.findMany({
      select: {
        id: true,
      },
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant