微信小程序:联表查询

参考:
https://blog.csdn.net/weixin_47077674/article/details/106481821?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-2.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-2.no_search_link

https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/aggregate/Aggregate.lookup.html#%E7%A4%BA%E4%BE%8B

代码解释

  1. 三张表:发布信息表v1_dailyReport、点赞表v1_zans、评论表v1_comments
  2. 关联关系:点赞表和评论表中记录的发布信息表的主键,reportId == _id
  3. 通过两次lookup,关联了点赞表和评论表
  4. 注意,最后需要return
// 按年月查询发布信息,含点赞和评论
async function searchDailyReportIncloudZansComments(event, wxContext) { 
  try {
    return await db.collection('v1_dailyReport').aggregate()
    .lookup({
      from: 'v1_zans',
      localField: '_id',
      foreignField: 'reportId',
      as: 'zansList',
    })
    .lookup({
      from: 'v1_comments',
      localField: '_id',
      foreignField: 'reportId',
      as: 'commentsList',
    })
    .match({
      classId: event.classId,
      certainYear: event.certainYear,
      certainMonth: event.certainMonth,
      dataStatus: 1
    })
    .sort({
      'issueDate': -1,
      'createDate': -1
    })
    .limit(1000)
    .end()    
    .then(res => {
      // console.log('res', res)
      return res
    })
  } catch (e) {
    console.error('error', e)
  }
}

你可能感兴趣的:(微信小程序:联表查询)