到目前为止,我有这个简单的架构:
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?
我知道这个架构不对,因为即使我删除了一个房间,房间引用也不会从引用它的会话中删除。
提前致谢!
答案 0 :(得分:2)
您可以在房间架构中创建对事件的引用。然后使用schema.pre中间件删除主要父房间中删除的sessions.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.
);
});