简体   繁体   中英

How to create company and branch relationship using Mongoose framework(Mongodb)?

I have a collection in mongo which has all the details for companies.

var companyModel = mongoose.model('company', new Schema({
  name: {type: String},
  address: {type: String},
  state: {type: String},
  city: {type: String},
  phoneNo: {type: Number},
  childsNo: {type: Number},
  poc: {type: Number},
  subscribtion: {type: Number}
}, {versionKey: false}));

from the above data, there are individual companies as well as company branches. Companies and branches have same details, So I want to maintain a single collection but want to differentiate the difference between a company and branch. I have only one level of branch.

After I design a collection, I should be able to find which company have which branch, If there are no branches it should say there are no branches.

Please let know the best design for this?

A one to many relationship from Companies to Branches. Let branches have a reference to their parent company as well.

var companyModel = mongoose.model('company', new Schema({
 ...
 branches : [{type : mongoose.Schema.Types.ObjectId, ref : 'branch'}]
 ...
});
var branchModel = mongoose.model('branch', new Schema({
 ...
 parent : { type : mongoose.Schema.Types.ObjectId, ref : 'company' }
 ...
});

The rest is just proper use of the $in operator, which you can find here .

You can achieve this by simply defining the branch schema withing the company schema. However a more cleaner way is to define the branch schema separately, but have it nested within the company schema. Below are both implementations:

First implementation:

var companyModel = mongoose.model('company', new Schema({
  ...
  branches: [{name: String}]
  ..
});

Second implementation (much cleaner in my opinion):

var Branch = new mongoose.Schema({
  name: String
});
var companyModel = mongoose.model('company', new Schema({
  ...
  branches: [Branch]
  ...
});

Either way, you still have your array of branches within the company model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM