Mongoose - 在父文档中引用嵌入的 id
Mongoose - reference an embedded id in the parent document
到目前为止我有这个简单的模式:
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?
我知道这个架构不正确,因为即使我删除了一个房间,房间引用也不会从引用它的会话中删除。
提前致谢!
您可以在房间 schema.Then 中创建对事件的引用,每当您对主父房间进行删除时,使用 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.
);
});
到目前为止我有这个简单的模式:
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?
我知道这个架构不正确,因为即使我删除了一个房间,房间引用也不会从引用它的会话中删除。
提前致谢!
您可以在房间 schema.Then 中创建对事件的引用,每当您对主父房间进行删除时,使用 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.
);
});