feat: add auto-increment userId (8-digit padded) to User model and login response

This commit is contained in:
Developer
2026-05-13 20:41:58 +08:00
parent 67e7c251a6
commit 9f2f9ba7f6
2 changed files with 247 additions and 222 deletions
+5
View File
@@ -12,6 +12,11 @@ const userSchema = new mongoose.Schema({
sparse: true,
index: true
},
userId: {
type: String,
unique: true,
index: true
},
nickname: {
type: String,
default: ''
+21 -1
View File
@@ -4,6 +4,23 @@ const axios = require('axios');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
async function generateUserId() {
const lastUser = await User.findOne({ userId: { $exists: true } })
.sort({ userId: -1 })
.select('userId')
.lean();
let nextNumber = 1;
if (lastUser && lastUser.userId) {
const lastNumber = parseInt(lastUser.userId, 10);
if (!isNaN(lastNumber)) {
nextNumber = lastNumber + 1;
}
}
return nextNumber.toString().padStart(8, '0');
}
router.post('/wechat-login', async (req, res, next) => {
try {
const { code, userInfo } = req.body;
@@ -40,9 +57,12 @@ router.post('/wechat-login', async (req, res, next) => {
let user = await User.findOne({ openid });
if (!user) {
const userId = await generateUserId();
user = await User.create({
openid,
unionid: unionid || undefined,
userId,
nickname: userInfo?.nickName || '',
avatarUrl: userInfo?.avatarUrl || '',
profile: {
@@ -72,7 +92,7 @@ router.post('/wechat-login', async (req, res, next) => {
data: {
token,
user: {
id: user._id,
userId: user.userId,
nickname: user.nickname,
avatarUrl: user.avatarUrl,
status: user.status,