I am creating a store API.
I am trying to filter out the result using the field from req.query and select. Everything else works fine except the select.
Error: TypeError: result.select is not a function
if (field) {
const sortField = field.split(",").join(" ");
result = result.select(sortField);
}
Not sure why is the select not a function.
CodePudding user response:
From the image, looks like result
is a unresolved promise when you call the select
.
Also, there's no select
method for an array (witch I believe, is what you're trying to filter out); instead you can use filter
Try this:
let newResult;
if (field && result) {
const sortField = field.split(",").join(" ");
newResult = result.filter(x=> x === sortField);
}
CodePudding user response:
Try with:
let products;
if (field) {
products = await product.find(queryObject).select(field.split(',').join(' '));
} else {
products = await product.find(queryObject);
}
res.status(200).json({ products, number: products.length });