V
V
Vladislav2017-06-17 15:47:46
MongoDB
Vladislav, 2017-06-17 15:47:46

How to properly build a mongodb + mongoose structure?

Hello. I decided to make RestAPI for diploma on nodejs + express + mongodb (mongoose).
I have already reviewed the structure of collections in mongo 3 times, but I just can’t find the optimal one. The theme of the diploma is automated parking.
I tried this: There are 3 collections (cars, users, and the actual list of entries / exits).
Car collection: car ID, car number, color (maybe some other parameters)
Users collection: first name, last name, date of birth, date added to the database and (array with car ID) ?
Entry/exit collection: car id, date-time, type(entry/exit)
Provided that a user can have more than 1 car and that a car can be without an attached user.
But I don’t understand how to then connect these collections in order to get, for example, a list of cars owned by the user through RestAPI? or for example statistics of entries / exits for all numbers of the user's car?
What should be the key field? According to the idea, the ID is auto, but the user will have an array of these IDs, how can I get information on all of them?
I tried the scheme when the user has information on the car inside, but then it turns out that the car cannot be without an attached user.
I know that mongoose has "Population", but how to use them if you have an array of strings in 1 table, and a string in another. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RidgeA, 2017-06-17
@RidgeA

In the document in the user's collection - an array with id records from the collection of cars - those cars. which belong to the user.
With such a scheme, it can be difficult to pull machines that are not bound to a user - to simplify this, you can bind all orphan machines to a "virtual user".
In general the described task, IMHO, is much better to lay down on relational .
There is no join in mongodb. There is a similar analogue of lookup, but it may not work.
in extreme cases, you will need to join in the code: get a user - get all the user's cars - get visit statistics for all the user's cars.
Something like this...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question