mongoose双向模式/多对多的关系

mongoose相当新,所以我正在寻找最好的方法来做到这一点。 我有两个模型: UsersCompanies 。 用户可以有很多公司,公司可以有很多用户。

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

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

然后我可以使用.populate('users')来获取关联用户的列表。 那里没问题。

我想知道的是,让所有companiesuser相关联的最有效/最好的方法是什么? 我不想像上面那样做,因为列表可能会不同步。 有没有办法,当我更新公司的用户,用户的公司也更新?

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

我还没有find一种方法来填充两种方式工作。

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

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