A
A
Alex_mos2020-07-14 08:54:57
MongoDB
Alex_mos, 2020-07-14 08:54:57

How to add data to existing mongodb collection document?

There is a React application that sends requests to the Node, express (mongoose) server, which in turn writes data to mongodb.

On the main page there is a Select from which information is obtained and when the button is pressed, the data is sent to the server, saved in the database and the transition to the second page takes place.
On the second page, there are also two Selects from which information is collected and should also be saved to the collection, in the document that was created from the first Select, but a new document with data is created.

How can I assign one document per user so that each user has their own document in the mongodb collection.
Advise where it is possible to find the information about it and to esteem.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex_mos, 2020-07-19
@Alex_mos

In general, I found a solution, maybe it's not quite right)))
Maybe someone will tell you it's worth doing this.
In React, when visiting a site, the user is given a number (which is generated from Date.now()) which is stored in sessionStorage. When data is sent to the server for the first time, this id is also sent to the server and to the database.
On the server, its value is exported to the second page, where the data from the second Select comes.
In the database, we look for a document in mongodb by id (which was in sessionStorage and imported to the second page) and write data to it. As a result, it turns out to write all the data into the document that was created when the data was first sent to the database.

R
Robur, 2020-07-14
@Robur

should also be saved to the collection, in the document that was created from the first Select, but a new document with data is created.

Obviously, instead of updating an existing one, you are creating a new one. To change this, you need to stop creating a new one, and instead update an existing one. Here upsert will suit you.
How can I assign one document per user so that each user has their own document in the mongodb collection.

save some user id in each document, then every time you look for whether there is already a document for the desired id, if there is, update it, if not, create a new one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question