Search code examples
node.jstypescriptmongodbprisma

gte and lte in prisma & mongodb


The error message "Type '{ $gte: number; $lte: number; }' is not assignable to type 'number'" indicates that you are trying to assign an object with $gte and $lte properties to a variable that expects a single number. This is because the location field in your Prisma model is defined as a Location type, which includes both long and lat properties.

async getStaffsByDutyAndLocation(req: Request, res: Response) {
  const { duty, location } = req.body;
  try {
    const staffs = await StaffController.prisma.staff.findMany({
      where: {
        duty,
        location: {
          long: {
            $gte: parseFloat(location.long) - 0.5,
            $lte: parseFloat(location.long) + 0.5,
          },
          lat: {
            $gte: parseFloat(location.lat) - 0.5,
            $lte: parseFloat(location.lat) + 0.5,
          },
        },
      },
    });
  };
}

I keep getting the error: "Type '{ $gte: number; $lte: number; }' is not assignable to type 'number'."

Location type:

type Location {
  address String?
  long Float
  lat Float
  other String?
}

expecting to get all staff within the location


Solution

  • Prisma uses gte and lte without the $ prefix. So instead of $gte and $lte, you should use gte and let.

       const staffs = await StaffController.prisma.staff.findMany({
          where: {
            duty,
            AND: [
              {
                location: {
                  long: {
                    gte: parseFloat(location.long) - 0.5,
                    lte: parseFloat(location.long) + 0.5,
                  },
                },
              },
              {
                location: {
                  lat: {
                    gte: parseFloat(location.lat) - 0.5,
                    lte: parseFloat(location.lat) + 0.5,
                  },
                },
              },
            ],
          },
        });