2
I’m trying to capture a certain product for your ID
using the filter
but there are some problems. It is only returning an empty array.
The products are stored within Categories, that is, there is an array (products
) intended only for products of each category.
Structure of JSON Categories
[
{
"color": "blue",
"_id": "5da5c64983f7162720710e81",
"user_id": "5d9cc90b7120712fc4371f66",
"name": "Bebida",
"createdAt": "2019-10-15T13:14:49.748Z",
"updatedAt": "2019-10-28T21:14:31.816Z",
"__v": 3,
"products": [
{
"_id": "5db4da74316b5142042d3c42",
"code": "2",
"name": "Coca Cola 1L",
"price": 7
}
]
},
{
"color": "blue",
"_id": "5db4e706f9400f41ccab9d66",
"user_id": "5d9cc90b7120712fc4371f66",
"name": "Lanche",
"products": [
{
"_id": "5db4e71ff9400f41ccab9d67",
"code": "3",
"name": "X Salada",
"price": 8
}
],
"createdAt": "2019-10-27T00:38:30.812Z",
"updatedAt": "2019-10-27T00:38:56.001Z",
"__v": 1
}
]
Structure of JSON Products
[
[
{
"_id": "5db4da74316b5142042d3c42",
"code": "2",
"name": "Coca Cola 1L",
"price": 7
}
],
[
{
"_id": "5db4e71ff9400f41ccab9d67",
"code": "3",
"name": "X Salada",
"price": 8
}
]
]
Code
async update(req, res){
try{
const { id, category_id } = req.params;
const { code, name, description, price } = req.body;
if (!id ||!category_id || !code || !name || (!price && price != 0))
return res.status(400).json({ success: false, message: "Empty data" });
// Capturando todas as categorias
const categories = await Category.find({ user_id: req.user_id });
if (!categories[0])
return res.status(200).json({ success: false, message: "No categories found" });
// Capturando apenas os produtos de todas as categorias
const products = categories.map((_categories) => {
return _categories.products;
});
// Capturando um produto pelo ID fornecido
const product = products.filter((_product) => {
if (_product._id == id)
return _product;
});
return res.json(product);
}catch(err){
return res.status(500).json({ success: false, message: "System error" });
}
}
Return
[]
Perhaps it would be better to turn this text into a comment attached to the question.
– Augusto Vasques