Answer the question
In order to leave comments, you need to log in
How to pull data from an array of objects?
Good day everyone!
I'm completely new to backend (and development in general). Stuck for two weeks with one problem that arose due to my ignorance. Therefore, I ask for an expert opinion from those who know)
I have collections in mongo - Order and Goods. I generated IDs for them using uuid (I don’t know if this info is important or not).
The Order object stores an array of products (items[]) with the id and quantity of a specific product:
Order = {
_id: '123123123123123',
items: [
{
_id: '0001',
quantity: 1
},
{
_id: '0002',
quantity: 4
}
]
}
Items = [
{
_id: '0001',
title: 'Pizza',
price: 650,
description: 'Some text'
},
{
_id: '0002',
title: 'Pasta',
price: 500,
description: 'Some text'
}
]
class testController {
async getTestOrder(req, res) {
try {
const id = req.params.id
const order = await Order.findOne({_id: id})
const items = await Item.find({})
for (let i =0; i < order.items.length; i++){
for (let j = 0; j < items.length; j++){
if(order.items[i]._id === items[j]._id){
order.items.push(items[j]) // не знаю как добавить новые данные, при это оставив quantity
}
}
}
res.send(order)
} catch (error) {
console.log(error);
res.status(404).json({message: 'Order was not found'})
}
}
}
Order = {
_id: '123123123123123',
items: [
{
_id: '0001',
quantity: 1,
title: 'Pizza',
price: 650,
description: 'Some text'
},
{
_id: '0002',
quantity: 4,
title: 'Pasta',
price: 500,
description: 'Some text'
}
]
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question