I am having troubles understanding the proper way to scale database migrations with multiple developers, multiple environments, including a production database with many users using ts-migrate-mongoose. The example provided in github is very simplistic and doesn’t really show how to do migrations with evolving schemas. It simply has a static schema, and a migration is run to populate the database with some initial data, and I can’t really find any real examples online either.
Lets take the classic example and extend it. Lets say I have
interface IUser {
_id: string;
name: string;
}
const User = new Schema<IUser>({
_id: { type: String, required: true },
name: { type: String, required: true }
})
and I want to update it to:
interface IUser {
_id: string;
firstName: string;
lastName: string;
}
const User = new Schema<IUser>({
_id: { type: String, required: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true }
})
I could write some migration like
const up = async () => {
const users = await User.find();
const updates = users.map((user) => {
const firstName = user.name.split(" ")[0];
const lastName = user.name.split(" ")[1];
return user.updateOne({$set: {firstName, lastName}})
});
await Promise.all(updates)
};
const down = async () => {
// ... corresponding down migration
}
but this will start giving me type errors when I change the interface and the model definitions. Then lets say, I have many more migrations, for the sake of example lets say I’m on the 5th migration, and I have a developer back on the first migration. Now its possible I could define new Schemas and models for each migration file, but if doing multiple migrations I start getting error:
Cannot overwrite `User` model once compiled.
One possible solution to this is to add:
delete (mongoose.connection.models as any)["User"];
at the top of the migration file. But is this really the best way to go about this? Really just looking for some general advice on how to do these database migrations with evolving schemas. Please let me know if any clarification is needed. Thanks