E
E
EugeneMedvedev2021-10-15 15:46:21
Node.js
EugeneMedvedev, 2021-10-15 15:46:21

How to make links between collections?

There are 3 models:
League - name
Season - name Match -
homeTeamName, awayTeamName, score?, date

It is necessary to make it so that when choosing a league there is a search by seasons, when choosing a season, search by matches. Please tell me how to do it correctly and how to link it so that when creating a match there is a connection for the season and the season is already in the league?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lssssssssssl, 2021-10-15
@EugeneMedvedev

Create in the League model

seasonId: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Season' }]

Create in the Season model
matchId: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Match' }]

Create a League - leagueModel.create(leagueData)
Create a Season - seasonModel.create(seasonData)
After creating a season, update the desired league by adding the id of the created season to it -
leagueModel.updateOne({ _id: leagueId }, { $push: { seasonId: inputSeasonId } })

To get a list of league seasons, do
leagueModel.findById(leagueId).populate('seasonId')

This is the connection of the League with the Seasons. Similarly, you make the connection of the Season with the matches.
Something like this. I didn't go into too much detail, but it should be clear.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question