UNPKG

@tasolutions/express-core

Version:
95 lines (79 loc) 4.04 kB
'use strict'; const _ = require('lodash'); const mongoose = require('mongoose'); module.exports = { searchByObjectIdField: async (query, req, collection) => { const { search } = req.query; if (search) { const regexSearch = { $regex: search, $options: 'i' }; const objectIdTypes = ['ObjectId', 'ObjectID']; // Lấy tất cả các trường có kiểu ObjectId từ schema const objectIdFields = Object.keys(collection.schema.tree).filter(key => { const path = collection.schema.path(key); return path && objectIdTypes.includes(path.instance) && path.options && path.options.ref; // Kiểm tra nếu có ref }); // Tìm kiếm trên mỗi trường ObjectId mà có ref for (const field of objectIdFields) { const modelName = collection.schema.path(field).options.ref; // Lấy tên model từ options.ref const Model = getModelFromRef(modelName); // Nhận mô hình // Lấy các trường của Model để tìm kiếm let keySchema = Object.keys(Model.schema.tree); keySchema = _.without(keySchema, 'id', '_id', '__v'); const keyVirtuals = Object.keys(Model.schema.virtuals); keySchema = keySchema.filter(item => !keyVirtuals.includes(item)); // Tạo điều kiện tìm kiếm cho tất cả các trường của model const searchConditions = keySchema.map(key => { const path = Model.schema.path(key); if (path && path.instance === 'String') { return { [key]: regexSearch }; // Tìm kiếm cho các trường kiểu String } return null; // Tránh thêm điều kiện nếu không phải String }).filter(condition => condition !== null); // Lọc các điều kiện null // Thực hiện tìm kiếm nếu có điều kiện if (searchConditions.length > 0) { const foundDocument = await Model.findOne({ $or: searchConditions }).select('_id'); if (foundDocument) { query[field] = foundDocument._id; // Cập nhật query với ObjectId tìm được } } } } return query; }, parseFormData: (data) => { if (!data) return {}; const result = {}; Object.keys(data).forEach(key => { const matches = key.match(/([^\[]+)\[([^\]]*)\]/); // Tìm nhóm và subKey if (matches) { const group = matches[1]; // Phần trước dấu '[' const subKey = matches[2]; // Phần giữa dấu '[' và ']' if (!result[group]) { if (subKey === "") { result[group] = []; // Khởi tạo mảng nếu không có subKey } else { result[group] = {}; // Khởi tạo đối tượng nếu có subKey } } if (subKey === "") { // Nếu subKey rỗng if (data[key] !== null) { result[group] = result[group].concat(data[key]); // Kết hợp mảng nếu không phải null } // Nếu null, không làm gì cả, giữ nguyên mảng rỗng } else { result[group][subKey] = data[key]; // Gán giá trị cho khóa con } } else { result[key] = data[key]; // Nếu không có lồng nhau thì thêm trực tiếp } }); return result; }, }; const getModelFromRef = (modelName) => { if (mongoose.models[modelName]) { return mongoose.models[modelName]; } else { throw new Error(`Model ${modelName} not defined`); } };