feat: UserEquity创建/删除/批量创建后自动更新User.platformCount;新增修复脚本

This commit is contained in:
Developer
2026-05-18 19:45:26 +08:00
parent 58b74257c7
commit e2dae5942d
2 changed files with 42 additions and 0 deletions
+31
View File
@@ -0,0 +1,31 @@
const mongoose = require('mongoose');
const User = require('../src/models/User');
const UserEquity = require('../src/models/UserEquity');
async function fixPlatformCount() {
try {
await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/member-assistant');
console.log('MongoDB connected');
const users = await User.find({}).select('_id');
console.log(`Found ${users.length} users`);
let updated = 0;
for (const user of users) {
const count = await UserEquity.countDocuments({ owner: user._id });
await User.findByIdAndUpdate(user._id, { platformCount: count });
updated++;
if (updated % 100 === 0) {
console.log(`Progress: ${updated}/${users.length}`);
}
}
console.log(`Done! Updated ${updated} users.`);
process.exit(0);
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
}
fixPlatformCount();
+11
View File
@@ -2,6 +2,12 @@ const express = require('express');
const router = express.Router();
const { auth } = require('../middleware/auth');
const UserEquity = require('../models/UserEquity');
const User = require('../models/User');
async function updateUserPlatformCount(userId) {
const count = await UserEquity.countDocuments({ owner: userId });
await User.findByIdAndUpdate(userId, { platformCount: count });
}
const requireVip = (req, res, next) => {
if (!req.user.isVip) {
@@ -174,6 +180,7 @@ router.post('/', auth, requireVip, async (req, res, next) => {
if (updateTime) equityData.updateTime = updateTime;
const equity = await UserEquity.create(equityData);
await updateUserPlatformCount(req.user._id);
res.status(201).json({
success: true,
@@ -252,6 +259,8 @@ router.post('/batch', auth, requireVip, async (req, res, next) => {
}
}
await updateUserPlatformCount(req.user._id);
res.status(201).json({
success: true,
data: {
@@ -424,6 +433,8 @@ router.delete('/:id', auth, requireVip, async (req, res, next) => {
});
}
await updateUserPlatformCount(req.user._id);
res.json({
success: true,
message: '权益已删除'