I am currently working on a price search engine with NodeJS and Mongoose and have a question about the implementation of a price matrix.
Each product has an icon, a type symbol, a width, a height and a price. For example, I have a product with the symbol: T5, type symbol: F, width: 900, height: 210 and price: 322.
The price matrix contains consecutive values as follows:
- Width: 1000, Height: 210, Price: 345
- Width: 1200, height: 210, price: 398
- Width: 1400, Height: 210, Price: 449
My problem is that when searching for the next price value, my code selects the next but one value if the value searched for is between two existing values. For example, for a width of 1160, the value for 1400 is selected directly instead of 1200.
Here is my code:
Translated with DeepL.com (free version)
const symbol = findProfil.symbol;
const typsymbol = product.symbol;
const findPrice = await profilSubPriceModel.aggregate([
{
$match: {
symbol: symbol,
typSymbol: typsymbol
}
},
{
$addFields: {
wide: { $toInt: "$wide" }, // Konvertieren von wide von String zu Int
height: { $toInt: "$height" } // Konvertieren von height von String zu Int
}
},
{
$addFields: {
wideDiff: { $abs: { $subtract: ["$wide", inputWidth + 65]}},
heightDiff: { $abs: {$subtract: ["$height", inputHeight + 45]}}
}
},
{
$addFields: {
validWidth: { $ceil: { $divide: [{ $toInt: "$wide" }, 100] } },
validHeight: { $ceil: { $divide: [{ $toInt: "$height" }, 100] } }
}
},
{
$addFields: {
totalDiff: { $add: ["$wideDiff", "$heightDiff"] }
}
},
{
$sort: { totalDiff: 1 }
},
{
$limit: 3
}
]);
How can I change my code so that the correct next value in the matrix is selected instead of the next but one value?
I keep getting the same value.
if (findPrice.length === 0) {
const findLargerPrice = await profilSubPriceModel.aggregate([
{
$match: {
symbol: symbol,
typSymbol: typsymbol
}
},
{
$addFields: {
wide: { $toInt: "$wide" },
height: { $toInt: "$height" }
}
},
{
$addFields: {
wideDiff: { $subtract: ["$wide", inputWidth] },
heightDiff: { $subtract: ["$height", inputHeight] }
}
},
{
$match: {
wideDiff: { $gte: 0 },
heightDiff: { $gte: 0 }
}
},
{
$addFields: {
totalDiff: { $add: ["$wideDiff", "$heightDiff"] }
}
},
{
$sort: { totalDiff: 1 }
},
{
$limit: 3
}
]);
if (findLargerPrice.length > 0) {
findPrice.push(...findLargerPrice);
}
}
Savas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.