convertWhereClause()

in packages/better-auth/src/adapters/mongodb-adapter/mongodb-adapter.ts [151:220]


		convertWhereClause(where: Where[], model: string) {
			if (!where.length) return {};
			const conditions = where.map((w) => {
				const { field: _field, value, operator = "eq", connector = "AND" } = w;
				let condition: any;
				const field = getField(_field, model);
				switch (operator.toLowerCase()) {
					case "eq":
						condition = {
							[field]: serializeID(_field, value, model),
						};
						break;
					case "in":
						condition = {
							[field]: {
								$in: Array.isArray(value)
									? serializeID(_field, value, model)
									: [serializeID(_field, value, model)],
							},
						};
						break;
					case "gt":
						condition = { [field]: { $gt: value } };
						break;
					case "gte":
						condition = { [field]: { $gte: value } };
						break;
					case "lt":
						condition = { [field]: { $lt: value } };
						break;
					case "lte":
						condition = { [field]: { $lte: value } };
						break;
					case "ne":
						condition = { [field]: { $ne: value } };
						break;

					case "contains":
						condition = { [field]: { $regex: `.*${value}.*` } };
						break;
					case "starts_with":
						condition = { [field]: { $regex: `${value}.*` } };
						break;
					case "ends_with":
						condition = { [field]: { $regex: `.*${value}` } };
						break;
					default:
						throw new Error(`Unsupported operator: ${operator}`);
				}
				return { condition, connector };
			});
			if (conditions.length === 1) {
				return conditions[0].condition;
			}
			const andConditions = conditions
				.filter((c) => c.connector === "AND")
				.map((c) => c.condition);
			const orConditions = conditions
				.filter((c) => c.connector === "OR")
				.map((c) => c.condition);

			let clause = {};
			if (andConditions.length) {
				clause = { ...clause, $and: andConditions };
			}
			if (orConditions.length) {
				clause = { ...clause, $or: orConditions };
			}
			return clause;
		},