const UserModel = require('../models/userModel') const { SearchResult } = require('../models/Search') exports.startTransaction = async () => { const seesion = await UserModel.startSession() seesion.startTransaction() return seesion } exports.commitTransaction = async (session) => { return await session.commitTransaction() } exports.rollbackTransaction = async (session) => { return await session.abortTransaction() } exports.selectAllUser = async () => { return await UserModel.find() } exports.selectUserList = async (search = {}) => { try { const { size = 20, page = 1, sort, filters } = search const skip = (page - 1) * size const searchResult = new SearchResult() searchResult.num = page searchResult.size = size // 检查 filters,确保只有在 filters 存在时才应用 const matchFilters = filters ? { ...filters } : {} const sortObj = sort && typeof sort === 'object' ? sort : { _id: 1 } // 默认按 _id 升序排序 const result = await UserModel.aggregate([ // 应用过滤条件,确保filters存在时才传入 { $match: matchFilters }, { $facet: { metadata: [{ $count: 'total' }, { $addFields: { total: '$total' } }], data: [{ $sort: sortObj }, { $skip: skip }, { $limit: size }] } } ]) // 解构 result 并进行必要的空值检查 const { metadata = [], data = [] } = result[0] || {} // 提取 metadata 中的 total,若不存在则为 0 searchResult.total = metadata.length > 0 ? metadata[0].total : 0 searchResult.list = data return searchResult } catch (error) { console.log(error) throw error } } exports.selectUserById = async (id) => { return await UserModel.findById(id) } exports.selectUserByAccount = async (account) => { return await UserModel.findOne({ account: account }) } exports.selectUserByEmail = async (email) => { return await UserModel.findOne({ email: email }) } exports.selectUserByUsername = async (username) => { return await UserModel.findOne({ username: username }) } exports.selectUserByPhone = async (phone) => { return await UserModel.findOne({ phone: phone }) } exports.selectUserByAccountExist = async (account) => { const exist = await UserModel.exists({ account: account }) return exist !== null } exports.createUser = async (user) => { return await UserModel.create(user) } exports.updateUserById = async (id, user) => { return await UserModel.findByIdAndUpdate(id, user) } exports.updateUserByLoginDate = async (id, loginDate) => { return await UserModel.findByIdAndUpdate(id, { last_login_date: loginDate }) } exports.deleteUserById = async (id) => { return await UserModel.findByIdAndDelete(id) } exports.deleteAllUser = async () => { return await UserModel.deleteMany() }