关于云开发数据库文档中,Aggregate下指定多个连接条件代码示例中错误的问题
发布于 5 年前 作者 afang 15054 次浏览 来自 官方Issues

在文档 https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/aggregate/Aggregate.lookup.html#%E7%A4%BA%E4%BE%8B 中,指定多个连接条件下的示例代码,缺少关键变量 const _ = db.command 的定义。

原文代码如下:

以下操作连接 orders 和 books 集合,要求两个条件:

  1. orders 的 book 字段与 books 的 title 字段相等
  2. orders 的 quantity 字段大于或等于 books 的 stock 字段
const db = cloud.database()
const $ = db.command.aggregate
db.collection('orders').aggregate()
  .lookup({
    from: 'books',
    let: {
      order_book: '$book',
      order_quantity: '$quantity'
    },
    pipeline: $.pipeline()
      .match(_.expr($.and([
        $.eq(['$title', '$$order_book']),
        $.gte(['$stock', '$$order_quantity'])
      ])))
      .project({
        _id: 0,
        title: 1,
        author: 1,
        stock: 1
      })
      .done(),
    as: 'bookList',
  })
  .end()
  .then(res => console.log(res))
  .catch(err => console.error(err))

示例代码中的 _.expr,并未在代码片段中定义变量 _ 导致直接复制代码后,根据业务表按需修改,出现报错的问题,解决此问题应当在

代码

const db = cloud.database()

const $ = db.command.aggregate

下,添加

const _ = db.command

进行定义。

正确的示例代码应当为:

const db = cloud.database()
const $ = db.command.aggregate
const _ = db.command
db.collection('orders').aggregate()
  .lookup({
    from: 'books',
    let: {
      order_book: '$book',
      order_quantity: '$quantity'
    },
    pipeline: $.pipeline()
      .match(_.expr($.and([
        $.eq(['$title', '$$order_book']),
        $.gte(['$stock', '$$order_quantity'])
      ])))
      .project({
        _id: 0,
        title: 1,
        author: 1,
        stock: 1
      })
      .done(),
    as: 'bookList',
  })
  .end()
  .then(res => console.log(res))
  .catch(err => console.error(err))
1 回复

你为文档完善做出了贡献。👍

回到顶部