A
A
Alex2021-06-02 07:19:36
Express.js
Alex, 2021-06-02 07:19:36

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
    }
  ]
}


Products look like this:
Items = [
  {
    _id: '0001',
    title: 'Pizza',
    price: 650,
    description: 'Some text'
  },
  {
    _id: '0002',
    title: 'Pasta',
    price: 500,
    description: 'Some text'
  }
]


Question: How to extract data about goods by id from the list of goods and write them to the order in order to send an order with full information about the goods to the front? Including title, price and description.

I tried to run loops and use forEach - but there was no result. Accessing a specific item in Order turns out (of the Order.items[0]._id type), but in the loop (of the Order.items[i]._id type) it gives an error that Order.items[i] is undefined.

Controller code:
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'})
        }
    }
}


As a result, you should get such a response to the front:
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'
    }
  ]
}


I will be grateful for help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-06-02
@bingo347

https://docs.mongodb.com/manual/reference/operator...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question