Does Mongoose ODM let you easily maintain both sides of an association?

If I have two models, with relation has_manyin ODM Mongoose. i.e. The user belongs to the Team, and Team has many users:

var User = new Schema({
  username    : {type: String, required: true },
  email       : {type: String, required: true},
  team        : { type: Schema.ObjectId, ref: 'Team'},
  created_at  : {type : Date, default : Date.now},
  updated_at  : {type : Date, default : Date.now}
});

var exports = module.exports = mongoose.model('User', User);

and

var Team = new Schema({
  name        : {type: String, required: true}, 
  users       : [{ type: Schema.ObjectId, ref: 'User'}], 
  created_at  : {type : Date, default : Date.now},
  updated_at  : {type : Date, default : Date.now}
});

var exports = module.exports = mongoose.model('Team', Team);

... is there a way to tell Mongoose to add userto the collection team.userson user.save({team: team, ...})? or do I just need to use middleware save()in the User model?

The reason I ask is because this is not one of the options for using Mongoose documents, and this functionality is pretty standard in the rails / mongoid convention.

+5
source share
1 answer

To answer your question: you will have to write this functionality yourself.

, ? , ? "has_many" .

0

All Articles