Home > Software design >  MongoDB - Insert 2 documents, each in another collection but share ObjectId
MongoDB - Insert 2 documents, each in another collection but share ObjectId

Time:01-11

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

CodePudding user response:

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}});

  • Related