0

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

Dufino
  • 33
  • 6
  • We need your db structure – Innovin Jan 10 '23 at 21:15
  • Are you also inserting user details? – Innovin Jan 10 '23 at 21:16
  • Yes, I am inserting company data to company collection and user data to user collection. I want to share IDs between them. Like I wrote in question - User is one collection and Company is another Collection. – Dufino Jan 10 '23 at 21:18
  • Well, your question lacks adequate information to help solve your issue – Innovin Jan 10 '23 at 21:19
  • Sorry, I that was not clear. I am inserting 2 separate data - for User like name, email,.. For Company I insert data like - company name, residence,... Each of these data get on insertion their own _id, but I want to connect them via other ids. How can I get that id on insertion when both are inserting on same time? Is there way to do it simply or I have to create one, create second with connected id of first then update first with second id? – Dufino Jan 10 '23 at 21:23
  • Now I get your point. gimme a sec – Innovin Jan 10 '23 at 21:39

1 Answers1

1

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 and company, get the IDs of both the user document and company document as such:

const user = User.save(yourData);
const company = Company.save(yourCompanyData);

Afterwards get the ids and use it to update the documents that are already stored as such:

const userId = user._id;
const companyId = company._id;

User.updateOne({_id: userId}, {$set: {companyId: companyId}});
Company.updateOne({_id: companyId}, {$set: {registeredByID: userId}});

So the complete code would be this:

const user = User.save(yourData);
const company = Company.save(yourCompanyData);
const userId = user._id;
const companyId = company._id;

User.updateOne({_id: userId}, {$set: {companyId: companyId}});
Company.updateOne({_id: companyId}, {$set: {registeredByID: userId}});

Innovin
  • 776
  • 1
  • 5
  • 19