Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/api/models/migrateEmail.ts
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove this

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import mongoose from "mongoose";
import dotenv from "dotenv";
import { User } from "./User";

dotenv.config();

const runMigration = async () => {
try {
if (!process.env.MONGO_URI) throw new Error("Missing MONGO_URI in .env");
await mongoose.connect(process.env.MONGO_URI);
console.log("Connected to DB.");

const users = await User.find({});
console.log(`Checking ${users.length} users...`);

for (const user of users) {
if (user.email) {
user.email = user.email.toLowerCase();
try {
await user.save();
console.log(`Fixed: ${user.email}`);
} catch (err: any) {
console.log(`Skipped (Duplicate or Error): ${user.email}`);
}
}
}

console.log("Done!");
process.exit();
} catch (e) {
console.error(e);
process.exit(1);
}
};

runMigration();
19 changes: 19 additions & 0 deletions src/api/models/userModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,25 @@ const userSchema = new Schema<IUser>(
},
);

//Pre-save hook
userSchema.pre("save", function (next){
if (this.isModified("email") && this.email){
this.email=this.email.toLowerCase();
}
next();
});

//Pre-find hook
userSchema.pre(/^find/, function (next){
const query=this as any;
const criteria=query.getFilter();

if (criteria.email && typeof criteria.email==="string"){
criteria.email=criteria.email.toLowerCase();
}
next();
});

const User = mongoose.model<IUser>("user", userSchema);
type PopulatedUser = mongoose.Document<
unknown,
Expand Down