1+ import { Db , ObjectId } from "mongodb" ;
2+
3+ const HEX24 = / ^ [ 0 - 9 a - f A - F ] { 24 } $ / ;
4+
5+ export async function up ( db : Db ) {
6+ try {
7+ const historiesToChange = await db
8+ . collection ( "histories" )
9+ . find ( { user : { $type : "string" , $regex : HEX24 } } )
10+ . toArray ( ) ;
11+
12+ if ( historiesToChange . length === 0 ) {
13+ console . log ( "No histories with string users to change." ) ;
14+ } else {
15+ const bulkOps = historiesToChange . map ( ( history ) => ( {
16+ updateOne : {
17+ filter : { _id : history . _id } ,
18+ update : {
19+ $set : {
20+ user : new ObjectId ( history . user as string ) ,
21+ migration_revert_flag : true ,
22+ } ,
23+ } ,
24+ } ,
25+ } ) ) ;
26+
27+ const result = await db . collection ( "histories" ) . bulkWrite ( bulkOps ) ;
28+ console . log ( `Converted ${ result . modifiedCount } history.user fields to ObjectId.` ) ;
29+ }
30+ } catch ( error ) {
31+ console . error ( "Migration UP failed:" , error ) ;
32+ throw error ;
33+ }
34+ }
35+
36+ export async function down ( db : Db ) {
37+ try {
38+ const historiesToRedefine = await db
39+ . collection ( "histories" )
40+ . find ( { migration_revert_flag : true } )
41+ . toArray ( ) ;
42+
43+ if ( historiesToRedefine . length === 0 ) return ;
44+
45+ const bulkOps = historiesToRedefine . map ( ( history ) => {
46+ const userIdString = history . user ? String ( history . user ) : null ;
47+
48+ return {
49+ updateOne : {
50+ filter : { _id : history . _id } ,
51+ update : { $set : { user : userIdString } } ,
52+ $unset : { migration_revert_flag : "" } ,
53+ } ,
54+ } ;
55+ } )
56+
57+ const result = await db . collection ( "histories" ) . bulkWrite ( bulkOps ) ;
58+ console . log ( `Reverted ${ result . modifiedCount } fields back to strings.` ) ;
59+
60+ } catch ( error ) {
61+ console . error ( "Migration DOWN failed:" , error ) ;
62+ throw error ;
63+ }
64+ }
0 commit comments