活着
新人入坑,不定时分享一些工作中遇到的一些问题,或者觉得好的点

活着ccc

新人入坑,不定时分享一些工作中遇到的一些问题,或者觉得好的点

记录一次moogdb 关联表查询

    getQuery (searchPanelData: any) {
        let _searchPanelData: any = {}
        if (!searchPanelData) {
            return _searchPanelData
        }
        Object.keys(searchPanelData).map((key: string) => {
            const item: any = searchPanelData[key]
            if (!item) {
                return
            }
            if (typeof item === 'string') {
                _searchPanelData[key] = new RegExp(item, 'i')
            } else if (Array.isArray(item) && item.length) {
                if (key === 'risk_type') {
                    _searchPanelData[key] = item
                } else {
                    _searchPanelData[key] = { '$in': item }
                }
            } else if (Object.prototype.toString.call(item) === '[object Object]') {
                const start = item['start']
                const end = item['end']
                _searchPanelData[key] = {
                    '$gte': start,
                    '$lte': end
                }
            }
        })
        return _searchPanelData
    }
   

getOffsetAndLimit (p: { pageSize?: number, page?: number } = {}): { offset: number, limit: number } { const limit = p.pageSize || 20 let page = p.page || 1 if (page <= 0) { page = 1 } const offset = (page - 1) * limit return { offset, limit, } } /** * 获取列表数据 * @param params * @returns */ async getList<T extends any> (params: ICurd.ICommonListParams) { const { pagination, query, sort, collection, env } = params let _query = this.getQuery(query) const [ riskCol ] = await this.mdbService.getCols({env, collections: [collection]}) // 联表查询 let cursor = await riskCol.aggregate([ { '$lookup': { // 关联的表 from: 'combo_relation_risk', // 用 localField 的字段 匹配 foreignField 的字段 localField: 'risk_code', foreignField: 'relation_risk_list', // 关联表的数据返回到 as 的字段中 as: 'relation_conbo_code_list' } }, // 查询条件 { '$match': { ..._query, _deleted: { '$nin': [true] } } } ]) const offsetAndLimit = { offset: 0, limit: 0 } if (pagination) { const { offset, limit } = this.getOffsetAndLimit(pagination) offsetAndLimit.offset = offset offsetAndLimit.limit = limit } if (pagination) { // 不传 pagination 则读取全部的数据,一般不推荐,前端无法获取全部数据 cursor.skip(offsetAndLimit.offset).limit(offsetAndLimit.limit) } cursor = cursor.sort(sort || { update_at: -1 }) const items = await cursor.toArray() const search = Object.assign({ _deleted: { '$nin': [true] } }, _query) // 获取总条数 const cursorV2 = riskCol.find(search) const count = await cursorV2.count() return { items, count, pagination } }

 

posted on 2022-07-01 14:40  活着ccc  阅读(18)  评论(0编辑  收藏  举报

导航