File tree 1 file changed +53
-0
lines changed
1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ import initDB from 'server/lib/db' ;
2
+ import { Event , User } from 'server/models' ;
3
+
4
+ async function deleteExpiredEventsAndUsers ( ) {
5
+ const db = await initDB ( ) ;
6
+
7
+ const oneWeekAgo = new Date ( ) ;
8
+ oneWeekAgo . setDate ( new Date ( ) . getDate ( ) - 7 ) ;
9
+
10
+ const session = await db . startSession ( ) ;
11
+ session . startTransaction ( ) ;
12
+
13
+ const expiredEvents = await Event . find ( { } ) ;
14
+
15
+ const eventIds = expiredEvents . map ( e => e . _id ) ;
16
+
17
+ await User . updateMany (
18
+ { } ,
19
+ {
20
+ events : {
21
+ $pullAll : { _id : eventIds } ,
22
+ } ,
23
+ } ,
24
+ { session } ,
25
+ ) ;
26
+
27
+ await User . deleteMany (
28
+ {
29
+ events : {
30
+ $size : 0 ,
31
+ } ,
32
+ } ,
33
+ // options for deleteMany is implemented but not typed
34
+ // https://github.com/Automattic/mongoose/pull/7860/files
35
+ // @ts -ignore
36
+ { session } ,
37
+ ) ;
38
+
39
+ await Event . deleteMany (
40
+ {
41
+ endsAt : { $gte : oneWeekAgo } ,
42
+ } ,
43
+ // same as above
44
+ // @ts -ignore
45
+ { session } ,
46
+ ) ;
47
+
48
+ await session . commitTransaction ( ) ;
49
+
50
+ console . log ( `success deleteExpiredEventsAndUsers since ${ oneWeekAgo } ` ) ;
51
+ }
52
+
53
+ deleteExpiredEventsAndUsers ( ) . then ( ( ) => process . exit ( 0 ) ) ;
You can’t perform that action at this time.
0 commit comments