skip to Main Content

Techstack:Next.js 14, MongoDB, Prisma ORM. I have a many documents in my DB but I need random 15 documents each time I request…

If I have to do the same thing using mongoose I can do this:

 const selectedProjects = await Project.aggregate([
  { $sample: { size: 15 } },
 ]).exec();

How can I accomplish the same in Prisma ORM?

2

Answers


  1. Chosen as BEST ANSWER

    Well, I have to make a function which shuffles the array and gives back

    
    function shuffleProjects(projects: Project[]): Project[] {
        // Deep copy the original array to avoid mutating the original array
        const shuffledProjects = [...projects];
    
        // Fisher-Yates shuffle algorithm
        for (let i = shuffledProjects.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffledProjects[i], shuffledProjects[j]] = [shuffledProjects[j], shuffledProjects[i]];
        }
    
        return shuffledProjects;
    }
    

    Then called

     const shuffledProjects = shuffleProjects(projects);
    
    

  2. Random results are not currently supported by Prisma. There’s an open feature request for it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search