我有一个关于删除多个引用的问题。我有3个架构模型 - >事件,发布和评论。事件存储对post(一对多)的引用和对注释的post store引用(one-to-many)。
事件架构
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = mongoose.Schema.Types.ObjectId;
const EventSchema = new Schema({
organizer: {
type: ObjectId,
required: true,
},
date: {
start: {
type: Date,
required: true,
},
end: {
type: Date,
required: true,
},
},
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
category: {
type: String,
required: true,
},
posts: [{
type: ObjectId,
ref: 'Post',
}],
});
module.exports = mongoose.model('Event', EventSchema);
发布架构
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = mongoose.Schema.Types.ObjectId;
const PostSchema = new Schema({
author: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now(),
required: true,
},
content: {
type: String,
required: true,
},
comments: [{
type: ObjectId,
ref: 'Comment',
}],
});
module.exports = mongoose.model('Post', PostSchema);
评论模式
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = mongoose.Schema.Types.ObjectId;
const CommentSchema = new Schema({
author: {
name: {
type: String,
required: true,
},
id: {
type: ObjectId,
required: true,
},
},
date: {
type: Date,
default: Date.now(),
},
content: {
type: String,
required: true,
},
});
module.exports = mongoose.model('Comment', CommentSchema);
现在看看这种情况:我删除了一个事件,所以我需要删除帖子(简单)和相关评论(ups!)。这是我的问题:如何使用他的所有引用轻松删除事件(删除事件会自动删除帖子和相关评论到这篇文章)?我真的不知道。谢谢你的帮助!
答案 0 :(得分:0)
0)阅读您要删除的活动
cont eventObj = Event.findOne({
_id: myEventId,
})
1)获取与要删除的事件相关的所有帖子
const posts = eventObj.posts;
const postObjs = Post.find({
_id: {
$in: posts,
},
});
2)获取与您要删除的帖子相关的所有评论
const comments = postsObjs.reduce((tmp, x) => [
...tmp,
...x.comments,
], []);
3)删除所有评论
Comments.remove({
_id: {
$in: comments,
},
});
4)删除所有帖子
Post.remove({
_id: {
$in: posts,
},
});
5)删除活动
Event.remove({
_id: {
$in: event,
},
});