wesbos
wesbos

Reputation: 26317

Mongoose bidirectional models / many to many relationships

Fairly new to mongoose so I'm looking for the best way to do this. I have two models: Users and Companies. A user can have many companies and a company can have many users.

Right now my Company Schema looks like this:

CompanySchema = new Schema
  name:
    type: String
    unique: true
  slug:
    type: String
  users: [
    type: Schema.Types.ObjectId
    ref: 'User'
  ]

And then I can use .populate('users') to get a list of associated users. No problem there.

What I'm wondering is, what is the most efficient/best way to get all companies associated with a user? I don't want to do the same as above as the lists could get out of sync. Is there a way that when I update a company's user that the user's companies are also updated?

Ideally, I could just do User.find().populate('companies')

Upvotes: 2

Views: 4069

Answers (1)

deedubs
deedubs

Reputation: 292

I haven't found a way to get populate to work both ways.

Normally we end up doing something like this

/**
 * Load the categories for this account
 * @method categories
 * @memberof Account
 * @instance
 * @param {Function} done 
 */
AccountSchema.methods.categories = function (done) {
  var Category = this.model('Category');

  return Category.find({account: this}, done);
};

Upvotes: 7

Related Questions