【问题标题】:Mongoose - reference an embedded id in the parent documentMongoose - 在父文档中引用嵌入的 id
【发布时间】:2015-02-28 20:48:48
【问题描述】:

到目前为止,我有这个简单的架构:

var room = new Schema(
  {
    name: { type: String, default: null, trim: true }
  });

var event = new Schema({
  name:            { type: String, default: null, trim: true },
  startDate:       Date,
  endDate:         Date,
  logo:            { type: Boolean, default: false },
  public:          { type: Boolean, default: false },
  rooms:           [room]
  sessions:        [
    {
      title:       { type: String, default: null, trim: true },
      description: { type: String, default: null, trim: true },
      date:        Date,
      start:       Number,
      end:         Number,
      room:        { type: Schema.Types.ObjectId, ref: 'room' }
    }
  ]
});

我知道如何引用另一个集合,但如何引用父文档中的嵌入 ID?

我知道这个架构不正确,因为即使我删除了一个房间,房间引用也不会从引用它的会话中删除。

提前致谢!

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以在房间架构中创建对事件的引用。然后在您对主父房间执行删除操作时使用 schema.pre 中间件删除 session.room 值。(确保从主房间删除 eventid架构)。另请参阅Removing many to many reference in Mongoose

    var room = new Schema({
        name: {
            type: String,
            default: null,
            trim: true
        },
        eventid: {
            type: Schema.Types.ObjectId, //Set reference to event here.
            ref: 'event'
        }
    });
    
    room.pre('remove', function(next) {//event is the schema name.
        this.model('event').update({; //this will have all the models,select the event 
                sessions.room: this._id//will have the room id thats being deleted
            }, {
                $pull: {
                    sessions.room: this._id//removes that array from the event.sessions.room
                }
            }, {
                multi: true
            },
            next();//continues and completes the room.remove.
        );
    });
    

    【讨论】:

      猜你喜欢
      • 2012-02-18
      • 2013-05-17
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2020-10-04
      • 2022-10-16
      • 2011-10-20
      • 2013-03-24
      相关资源
      最近更新 更多