'CastError when using variables but writing manually the same query works
I'm converting my price query into an array and then dividing them into variables to do a query with more than one filter per variable. The problem that i have is that doing this divition between the array and using them to do a query i get a CastError, but when i tipe the same string manually it works.
My model looks like this:
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "product name must be provided"],
},
price: {
type: Number,
required: [true, "product price must be provided"],
},
featured: {
type: Boolean,
default: false,
},
rating: {
type: Number,
default: 4.3,
},
createdAt: {
type: Date,
default: Date.now(),
},
company: {
type: String,
enum: {
values: [
"Nike",
"Adidas",
"Puma",
"Balenciaga",
"New Balance",
"Air Jordan",
"Reebok",
],
message: "{VALUE} is not avaiable",
},
},
img: {
type: String,
required: [true, "Image must be provided"],
},
});
module.exports = mongoose.model("Product", productSchema);
const { featured, company, name, sort, props, numericFilters, all } =
req.query;
var queryObject = {};
if (numericFilters) {
const operatorMap = {
">": "$gt",
">=": "$gte",
"=": "$eq",
"<": "$lt",
"<=": "$lte",
};
const regEx = /\b(<|>|>=|=|<|<=)\b/g;
let filters = numericFilters.replace(
regEx,
(match) => `-${operatorMap[match]}-`
);
const options = ["price", "rating"];
var arrayObjects = [];
var secondObject = {};
filters = filters.split(",").forEach((item) => {
const [field, operator, value] = item.split("-");
if (options.includes(field)) {
if (field == "price") {
if (arrayObjects != 0) {
secondObject = { [operator]: Number(value) };
arrayObjects.push(secondObject);
} else {
secondObject = { [operator]: Number(value) };
arrayObjects.push(secondObject);
}
queryObject[field] = arrayObjects;
} else {
queryObject[field] = { [operator]: Number(value) };
}
}
});
queryObject.price.reduce((a, v) => ({ ...a, [v]: v }), {});
}
var firstPrice = queryObject.price[0];
var secondPrice = queryObject.price[1];
let result = Product.find({ price: { firstPrice, secondPrice } });
First price and second look like this: { '$gt': 150 } { '$lt': 300 }
Using this i the error message i get is:
(node:11348) UnhandledPromiseRejectionWarning: CastError: Cast to Number failed for value "{ firstPrice: { '$gt': 150 }, secondPrice: { '$lt': 300 } }" (type Object) at path "price" for model "Product" I don't get why it shows the name of the variable and the object at the error message.
But if i type the query manually like this it works: let result = Product.find({ price: { $gt : 150, $lt: 300 } });
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
