1. 单条件模糊查询
router. post ( '/list' , ( req, res ) => {
const name = new RegExp ( req. body. name, 'i' ) ;
Client. find ( { name } ) . then ( ( data ) => {
res. send ( {
code : 200 ,
msg : '查询成功' ,
data
} )
} ) . catch ( ( e ) => {
console. log ( e)
res. send ( {
code : 500 ,
msg : '查询失败'
} )
} )
} )
2. 多条件模糊查询
router. post ( '/list' , ( req, res ) => {
const regFn = ( arr ) => {
const params = { }
arr. forEach ( key => {
if ( ! req. body[ key] ) return
params[ key] = new RegExp ( req. body[ key] , 'i' )
} ) ;
return params
}
Client. find ( regFn ( [ 'name' , 'phone' ] ) ) . then ( ( data ) => {
res. send ( {
code : 200 ,
msg : '查询成功' ,
data
} )
} ) . catch ( ( e ) => {
console. log ( e)
res. send ( {
code : 500 ,
msg : '查询失败'
} )
} )
} )
3. 分页查询
const errorTem = ( msg, error ) => res. send ( {
code : 500 ,
msg,
error
} ) ;
const successTem = ( msg, data ) => ( {
code : 200 ,
msg,
data
} )
router. post ( '/list' , ( req, res ) => {
let {
pageSize,
pageNo,
} = req. body
const regFn = ( arr ) => {
const params = { }
arr. forEach ( key => {
if ( ! req. body[ key] ) return
params[ key] = new RegExp ( req. body[ key] , 'i' )
} ) ;
return params
}
const find = Client. find ( regFn ( [ 'name' , 'phone' ] ) ) ;
find. then ( ( datas ) => {
find. limit ( pageSize) . skip ( pageSize * ( pageNo - 1 ) ) . then ( ( data ) => {
res. send ( successTem ( '查询成功' , {
data,
total : datas. length
} ) )
} ) . catch ( e => res. send ( errorTem ( '查询失败' , e) ) )
} ) . catch ( e => res. send ( errorTem ( '查询失败' , e) ) )
} )