S
S
Sergey Filnor2019-11-19 18:04:33
JavaScript
Sergey Filnor, 2019-11-19 18:04:33

How to properly build a query in MongoDB?

Good evening.
Tell me how to properly extract data from Mongo that has the following structure. There are three collections Contests, Groups, Fields - each of which links to the next one via id:

const Contest = { 
  ...
  group_ids: ['abc', 'def']
  ...
}

const Group = {
  ...
  title: 'Hello'
  ...
}

const Field = {
  ...
  fieldGroupId: 'abc'
}

Further, having these id groups in the competition, you need to pull out the data of the group itself and for each group return more fields that are attached to it.
That is, as a result, get this object:
const groups = [
  {
    gruop: GROUP_DATA,
    fields: GROUP_FIELDS
  },
  ...
]

I tried to get it like this, but here it is necessary to somehow resolve it, because as a result, two empty objects come.
Well, besides, I want to somehow optimize this piece of code so as not to make 50 queries to the database at a time.
let groups = contest.fields_groups.map( async ( group_id ) => {
    let group = await ContestGroups.findById( group_id );
    let fields = await ContestField.where({ fieldGroupId: group_id });
    
    return {
        group: group,
        fields: fields
    };
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2019-11-19
@filnor

aggregation and $lookup
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