I have this question: I want to insert 2 documents into 2 collections.
One is for user and one is for company.
Both inserts are requested via api.
In created(Inserted) company I want to know, which user[Created/inserted] create this company. And in user i want to have _id of company that he inserted.
User { _id: "userGeneratedId", companyId : Company._id }
Company { _id: "companyGeneratedId", registeredByID : user._id }
How can this be done?
Thank you, Dufino
There are two ways to go about this
The first and easy way
Add new fields to your user and company model. maybe call it
userSaveId
or whatever you choose. Now you will insert same unique id to these new fields fields, so that when you are retrieving a company, you can just retrieve it based on that ID.The second way this could be done is by performing 4 operations. 2 insert operations and two update operations. Note that this would slightly increase the response time of your operations.
Suppose you have inserted a
user
andcompany
, get theIDs
of both theuser document
andcompany document
as such:Afterwards get the ids and use it to update the documents that are already stored as such:
So the complete code would be this: