UNPKG

@tasolutions/express-core

Version:
54 lines (47 loc) 2.06 kB
const mongoose = require('mongoose'); const mongoosePaginate = require('mongoose-paginate-v2'); /** * Định nghĩa các trường cơ bản cho schema */ const baseSchemaFields = { is_active: { type: Boolean, default: true }, // Trạng thái hoạt động created_by_identifier: { type: String }, // Người tạo bản ghi is_deleted: { type: Boolean, default: false }, // Trạng thái xóa mềm deleted_at: { type: Date }, // Thời gian xóa deleted_by_identifier: { type: String }, // Người xóa bản ghi restored_at: { type: Date }, // Thời gian phục hồi restored_by_identifier: { type: String }, // Người phục hồi bản ghi }; /** * Hàm khởi tạo schema cơ bản * @param {Object} fields - Các trường bổ sung cho schema * @returns {mongoose.Schema} - Trả về một schema mới */ function baseSchema(fields) { const schema = new mongoose.Schema( { ...fields, ...baseSchemaFields }, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } } ); /** * Tìm một bản ghi theo ID * @param {string} _id - ID của bản ghi cần tìm * @returns {Promise<Object>} - Trả về bản ghi tìm thấy */ schema.statics.findByID = async function (_id) { return this.findOne({ _id }); }; /** * Kiểm tra sự tồn tại của bản ghi dựa trên trường và giá trị * @param {string} field - Tên trường cần kiểm tra * @param {string|number} value - Giá trị của trường cần kiểm tra * @returns {Promise<boolean>} - Trả về true nếu bản ghi tồn tại, ngược lại false */ schema.statics.isExistByField = async function (field, value) { const count = await this.countDocuments({ [field]: value }); return count > 0; }; // Thêm plugin cho phân trang schema.plugin(mongoosePaginate); return schema; } module.exports = { baseSchema }; // Xuất baseSchema để sử dụng trong các mô hình khác