2👍
You’re trying to find the ID from the response object itself. The response object has all kind of data related to the HTTP request response, but most of that is irrelevant to you.
The actual data that comes in the response is within the ‘data’ property of the response.
So simply access that data variable, for example by destructuring it, and then use the native find function of arrays:
const { data } = await axios.get('http://localhost:4200/products');
return data.find((product) => product._id === id)
Note that you can’t use the Mongoose’s findById function here. That is a function related to the database, but you’re not interacting with the database here, even though the HTTP request to get the products you want internally gets them from some database related to the other service.
2👍
Since you are looking for a specific ID in an array (data
) of products you need to filter out the data in your response from /products
.
app.get('/add-to-cart/:id', async (req, res) => {
let id = req.params.id;
let cart = new Cart(req.body.cart ? req.body.cart : {});
const { data } = await axios.get('http://localhost:4200/products')
const productId = data.find(el => el._id === id);
response.findById(productId)
});
1👍
You can achieve this with the following code:
const element = response.data.filter(e => e.id == <your_id>);