云数据库多集合查询

2021-01-16  本文已影响0人  泡杯感冒灵
有时候,我们需要查询多个集合,并把查询结果一起返回。例如当我们点击某篇博客的时候,我们不但要查询博客的内容详情, 还要查询博客的相关评论列表
  app.router('detail',async(ctx,next) => {
    let blogId = event.blogId
    // 详情查询
    //  let detail = await blogCollection.where({
    //   _id:blogId
    // }).get().then((res) => {
    //   return res.data
    // })

    // 评论查询
    // const countResult = await db.collection('blog-comment').count()
    // const total = countResult.total  // 集合里的数据条数
    // let commentList = {
    //   data:[]
    // }
    // if(total > 0){
    //   // 查询的次数
    //   const batchTimes = Math.ceil(total/MAX_LIMIT)

    //   const tasks = []
    //   for(let i = 0;i < batchTimes; i++){
    //     let promise = db.collection('blog-comment')
    //                   .skip(i*MAX_LIMIT)
    //                   .limit(MAX_LIMIT)
    //                   .where({
    //                     blogId
    //                   })
    //                   .orderBy('createTime','desc')
    //                   .get()
    //     tasks.push(promise)              
    //   }
    //   if(tasks.length > 0){
    //     commentList = (await Promise.all(tasks)).reduce((acc,cur)=>{
    //       return {
    //         data:acc.data.concat(cur.data)
    //       }
    //     })
    //   }
    // }
    // ctx.body = {
    //   commentList,
    //   detail
    // }

    // 聚合查询实现连表查询
    const blog = await blogCollection.aggregate().match({
      _id:blogId
    }).lookup({
      from:'blog-comment',
      localField:'_id',
      foreignField:'blogId',
      as:'commentList'
    })
    .end()
    ctx.body = blog
  })

  const wxContext = cloud.getWXContext()
  app.router('getListByOpenId',async(ctx,next) =>{
    ctx.body = await blogCollection.where({
      _openid:wxContext.OPENID
    }).skip(event.start).limit(event.count)
    .get().then((res) => {
      return res.data
    })
  })
  return app.serve()
}
上一篇 下一篇

猜你喜欢

热点阅读