Mongoose and MongoDB patterns — schema design, validation, indexes, virtuals,
99
99%
Does it follow best practices?
Impact
100%
1.11xAverage score across 5 eval scenarios
Passed
No known issues
An e-commerce company is building a product catalog service. They have a Product model with a pricing hook that automatically calculates a discountedPrice field based on the product's base price and any active promotions. The ops team has noticed reports that discounted prices are sometimes out of date after admin users update products through the dashboard — they suspect the recalculation logic isn't running consistently on every change.
Your task is to implement the data access layer for this catalog service. The service needs to: serve product listings to customers (high read volume, results go directly to API responses), let admins update product fields (including fields with schema validators like status and stock), and handle the pricing recalculation so that the discounted price stays consistent whenever product data is changed.
Write a TypeScript file at product-service.ts that implements the following three functions:
listProducts(filters) — returns all active products matching the given filters. Results are sent directly to the API response.updateProductAdmin(productId, updates) — updates a product's fields via admin action. Must enforce schema validation on the new values.updateProductPrice(productId, newBasePrice) — updates a product's base price and ensures the discounted price is recalculated and stays in sync with the new value.Also include the Product schema and model definition. The schema should have at minimum: name (string), status (one of: 'active', 'draft', 'archived'), basePriceCents (number), discountedPriceCents (number), stock (number with minimum 0). Add a Mongoose hook that sets discountedPriceCents to 90% of basePriceCents when the product is on promotion (you can hardcode onPromotion: true for this example).
No input files required.