Hi everyone,
I’m building a recipe API using Node.js, Express, and Mongoose. My MongoDB documents have nested nutrient fields stored as strings with units, for example:
{
"nutrients": {
"calories": "389 kcal",
"proteinContent": "5 g",
"fatContent": "21 g"
},
"serves": "8 servings",
"title": "Sweet Potato Pie"
}
I want to allow clients to filter recipes by numeric ranges, e.g., calories less than 300 kcal.
Problem:
Since calories is stored as "389 kcal" (string), MongoDB cannot perform $gt, $lt, $gte, $lte operations correctly.
I’m also storing serves as "8 servings" and other nutrients similarly with units.
Questions:
What is the best way to perform numeric comparisons for fields stored as strings with units?
Should I migrate the database to store numeric values and units separately?
If migration isn’t possible, how can I filter recipes efficiently — via aggregation or Node.js post-processing?
Top comments (0)