Aller au contenu principal

User Model Migration Guide

Overview

This migration consolidates user data into a unified User model, eliminating data duplication between ProtectionUser and NewsletterSubscribers. Both models now reference the central User model instead of storing user data directly.

Changes Summary

New Model: User

Location: BaldrTs/src/models/user.model.ts

Fields:

  • _id (ObjectId)
  • email (String, unique, required)
  • firstName (String, optional)
  • lastName (String, optional)
  • password (String, optional, hashed)
  • last_login (Date, optional)
  • createdAt (Date, auto)
  • updatedAt (Date, auto)

Updated Models

ProtectionUser Model

Before:

{
userName: string;
email: string;
password: string;
slug: string;
groups: ObjectId[];
module_id?: ObjectId;
active: boolean;
}

After:

{
user_id: ObjectId; // References User model
userName: string;
slug: string;
groups: ObjectId[];
module_id?: ObjectId;
active: boolean;
}

NewsletterSubscribers Model

Before:

{
email: string;
firstName: string;
lastName: string;
groups: ObjectId[];
active: boolean;
}

After:

{
user_id: ObjectId; // References User model
groups: ObjectId[];
active: boolean;
}

Migration Steps

1. Backup Your Database

mongodump --uri="your_mongo_uri" --out=backup_before_migration

2. Run the Migration Script

cd BaldrTs
npm run migrate:users

The script will:

  1. Create User records from existing ProtectionUser records (email + password)
  2. Create User records from existing NewsletterSubscriber records (email + names)
  3. Merge duplicate users by email
  4. Update ProtectionUser records with user_id references
  5. Update NewsletterSubscriber records with user_id references
  6. Remove old fields (email, password, firstName, lastName) from both models

3. Verify the Migration

# Check that users were created
mongo your_database --eval "db.users.count()"

# Check that protection users have user_id
mongo your_database --eval "db.protectionusers.findOne()"

# Check that newsletter subscribers have user_id
mongo your_database --eval "db.newslettersubscribers.findOne()"

4. Update Your Frontend Application

The frontend interfaces have been updated in Baldr-Bo/app/interfaces/:

  • New: baseUser.interface.ts
  • Updated: user.interface.ts (now IProtectionUser)
  • Updated: newsletterSubscribers.interface.ts

Update your API calls to work with the new structure where data is populated from user_id.

5. Deploy Backend Changes

Deploy the updated backend with:

cd BaldrTs
npm run build
npm start

API Changes

Protection Users

Before:

{
"_id": "123",
"userName": "john_doe",
"email": "john@example.com",
"password": "hashed...",
"groups": []
}

After:

{
"_id": "123",
"userName": "john_doe",
"user_id": {
"_id": "456",
"email": "john@example.com",
"firstName": "John",
"lastName": "Doe"
},
"groups": []
}

Newsletter Subscribers

Before:

{
"_id": "789",
"email": "jane@example.com",
"firstName": "Jane",
"lastName": "Smith",
"groups": ["group1"]
}

After:

{
"_id": "789",
"user_id": {
"_id": "456",
"email": "jane@example.com",
"firstName": "Jane",
"lastName": "Smith"
},
"groups": ["group1"]
}

New Endpoints

User Management

POST   /user              - Get all users (paginated)
POST /user/search - Search users
GET /user/:id - Get user by ID
GET /user/email/:email - Get user by email
POST /user/new - Create user
PUT /user/edit/:id - Update user (admin)
DELETE /user/delete - Delete users (admin)
PUT /user/last-login/:id - Update last login

Updated Behaviors

Protection User Login

  • Now updates last_login field in the User model
  • Returns user email from the referenced User model

Newsletter Creation

  • Automatically creates or finds a User by email
  • Links the newsletter subscriber to the User

Newsletter Unsubscribe

  • Looks up the User by email
  • Removes the newsletter subscriber linked to that User

Newsletter Cron

  • Populates user_id to get email addresses
  • Sends emails to active subscribers with valid user references

Rollback Procedure

If you need to rollback:

  1. Restore the database backup:
mongorestore --uri="your_mongo_uri" backup_before_migration
  1. Revert to the previous codebase version:
git revert HEAD

Benefits

  1. Data Consistency: Single source of truth for user data
  2. Reduced Duplication: Email and personal info stored once
  3. Better Relationships: Clear relationships between models
  4. Easier Updates: Update user info in one place
  5. Future Flexibility: Easy to add new features that reference users

Troubleshooting

Migration Script Fails

  • Check MongoDB connection string in .env
  • Ensure you have write permissions
  • Check logs for specific error messages

Duplicate Email Errors

  • The migration handles duplicates by merging them
  • If manual intervention needed, identify duplicates:
db.users.aggregate([
{ $group: { _id: "$email", count: { $sum: 1 } } },
{ $match: { count: { $gt: 1 } } }
])

Missing user_id After Migration

  • Re-run the migration script
  • Check that the User was created successfully
  • Verify the old documents had email fields

Support

For issues or questions, contact the development team or open an issue in the repository.