import { ObjectId } from 'bson' ; interface Dic { [ key ] : any ; } param data return export function convertFields ( data ) { let out = data ; out = convertOid ( out ) ; out = convertDate ( out ) ; return out ; } export function convertDate ( data ) { return convertField ( data , '$date' , field => new Date ( field ) ) ; } export function convertOid ( data ) { return convertField ( data , '$oid' , field => new ObjectId ( field ) ) ; } function convertField ( data , fieldName , converter ) { Object . keys ( data ) . forEach ( k => { if ( k === '$in' ) { data [ k ] = convertFieldIn ( data [ k ] , fieldName , converter ) ; } else { data [ k ] = convertFieldSub ( data [ k ] , fieldName , converter ) ; } } ) ; return data ; } function convertFieldSub ( item , fieldName , converter ) { if ( ! item ) { return item ; } else if ( Array . isArray ( item ) ) { return item . map ( e => convertFieldSub ( e , fieldName , converter ) ) ; } else if ( typeof ( item ) === 'object' ) { if ( item [ fieldName ] ) { const out = converter ( item [ fieldName ] ) ; if ( Array . isArray ( out ) ) { return { $in : out } ; } else { return out ; } } else { return convertField ( item , fieldName , converter ) ; } } else { return item ; } } function convertFieldIn ( values , fieldName , converter ) { values = values . map ( item => { if ( typeof ( item ) === 'object' && item [ fieldName ] ) { const out = converter ( item [ fieldName ] ) ; if ( Array . isArray ( out ) ) { return out ; } else { return [ out ] ; } } else { return [ item ] ; } } ) ; return values . reduce ( ( array , v ) => { return array . concat ( v ) ; } , [ ] ) ; }