小程序云开发模糊查询实现

const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate;


/**
 * 获取我的发布记录
 * @param {*} event 
 * @param {*} context 
 */
exports.main = async (event, context) => {
  let pageIndex = Number(event.page_index) - 1;
  let pageSize = Number(event.page_size);
  let matchData = {
    is_delete: '0'
  };

  if (event.is_lock) {
    if (event.is_lock === '0') {
      matchData.is_lock = _.neq('1')
    }
    // matchData.is_lock = event.is_lock;
  }

  if (event.is_hide_publish && event.is_hide_publish === '1') {
    matchData._openid = _.neq(event.openid);
  }

  let keyWord = event.keyword ? (event.keyword + '').trim() : '';

  if (keyWord) {
    matchData.comment = {
      $regex: '.*' + keyWord,
      $options: 'i'
    };
  }

  // matchData['follow_user._openid'] = event.openid;
  // 返回数据库聚合结果
  return db.collection('book_ring')
    .aggregate()
    .lookup({
      from: 'user_info',
      localField: '_openid',
      foreignField: '_openid',
      as: 'user_data'
    }).lookup({
      from: 'follow_user',
      localField: '_openid',
      foreignField: 'follow_openid',
      as: 'follow_data'
    })

    .lookup({
      from: 'book_ring_like_record',
      localField: '_id',
      foreignField: 'book_ring_id',
      as: 'like_record'
    })
    .match(matchData)
    .sort({
      'sort_data': -1
    })
    .skip(pageIndex * pageSize).limit(pageSize)
    .end()

};

  

关键代码:

 matchData.comment = {
      $regex: '.*' + keyWord,
      $options: 'i'
    };

 调用

    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {

      },
      data: {
        type: 'getReleaseRecord',
        page_index: pageIndex,
        page_size: pageSize,
        openid: openid,
        is_lock: '0',
        is_hide_publish: '0',
        keyword: _this.data.keyword
      }
    })

  

posted @ 2022-11-15 22:32  w1433189426  阅读(74)  评论(0编辑  收藏  举报