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:
- Create
Userrecords from existingProtectionUserrecords (email + password) - Create
Userrecords from existingNewsletterSubscriberrecords (email + names) - Merge duplicate users by email
- Update
ProtectionUserrecords withuser_idreferences - Update
NewsletterSubscriberrecords withuser_idreferences - 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(nowIProtectionUser) - 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_loginfield 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_idto get email addresses - Sends emails to active subscribers with valid user references
Rollback Procedure
If you need to rollback:
- Restore the database backup:
mongorestore --uri="your_mongo_uri" backup_before_migration
- Revert to the previous codebase version:
git revert HEAD
Benefits
- Data Consistency: Single source of truth for user data
- Reduced Duplication: Email and personal info stored once
- Better Relationships: Clear relationships between models
- Easier Updates: Update user info in one place
- 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.