Mongoose双向模型/多对多关系

wes*_*bos 1 database mongoose mongodb node.js express

相当新的猫鼬,所以我正在寻找最好的方法来做到这一点.我有两个型号:UsersCompanies.用户可以拥有许多公司,公司可以拥有许多用户.

现在我的公司架构看起来像这样:

CompanySchema = new Schema
  name:
    type: String
    unique: true
  slug:
    type: String
  users: [
    type: Schema.Types.ObjectId
    ref: 'User'
  ]
Run Code Online (Sandbox Code Playgroud)

然后我可以.populate('users')用来获取相关用户的列表.没问题.

我想知道的是,最有效/最好的方法companiesuser什么?我不想像上面那样做,因为列表可能不同步.有没有一种方法,当我更新公司的用户时,用户的公司也会更新?

理想情况下,我可以做到 User.find().populate('companies')

dee*_*ubs 6

我还没有找到一种方法来填充两种方式.

通常我们最终会做这样的事情

/**
 * 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);
};
Run Code Online (Sandbox Code Playgroud)