【问题标题】:Does mongoose ODM allow you to save both sides of an association easily?mongoose ODM 是否允许您轻松保存关联的双方?
【发布时间】:2012-02-21 09:00:43
【问题描述】:

如果我有两个模型,在 Mongoose ODM 中具有 has_many 关系。 IE。用户属于团队,团队有很多用户:

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);

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);

...有什么方法可以告诉 Mongoose 将 user 添加到 user.save({team: team, ...}) 上的 team.users 集合中?还是我只需要在 User 模型中使用 save() 中间件?

我问的原因是,这不是 Mongoose 文档涵盖的用例之一,而且这个功能在 rails/mongoid 约定中是相当标准的。

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    要回答您的问题:您必须自己编写该功能。

    但是,您是否通过schema design doc?具体链接与嵌入?通过文档嵌入来完成“has_many”关系通常更容易、更有效。

    【讨论】:

    • 是的,我有。我发现当没有父实体不存在实体时,嵌入是有意义的。我还发现显式查询嵌入式数据要困难得多。
    猜你喜欢
    • 2011-02-09
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多