gpt4 book ai didi

node.js - 删除多个引用

转载 作者:太空宇宙 更新时间:2023-11-04 01:56:55 25 4
gpt4 key购买 nike


我有一个关于删除多个引用的问题。我有 3 个模式模型 -> 事件、帖子和评论。事件存储对帖子的引用(一对多)和帖子存储对评论的引用(一对多)。

<小时/>

事件架构

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) 阅读您要删除的事件

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,
},
});

关于node.js - 删除多个引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47593970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com