删除多个参考
我有一个关于删除多个引用的问题。 我有3个模式模型 – >事件,发布和评论。 事件存储对post(一对多)的引用以及对商店引用的注释(一对多)。
事件模式
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!)。 这是我的问题:我如何轻松地删除事件与他的所有引用(删除事件自动删除post和相关评论到这个职位)? 我真的不知道。 感谢帮助!
0)阅读你想要删除的事件
cont eventObj = Event.findOne({ _id: myEventId, })
1)获取与该活动相关的所有post以删除
const posts = eventObj.posts; const postObjs = Post.find({ _id: { $in: posts, }, });
2)获取所有关于你想要删除的post的评论
const comments = postsObjs.reduce((tmp, x) => [ ...tmp, ...x.comments, ], []);
3)删除所有评论
Comments.remove({ _id: { $in: comments, }, });
4)删除所有post
Post.remove({ _id: { $in: posts, }, });
5)删除事件
Event.remove({ _id: { $in: event, }, });