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