在文档 https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/aggregate/Aggregate.lookup.html#%E7%A4%BA%E4%BE%8B 中,示例代码片段缺少关键变量 _ 的定义
指定多个连接条件假设 orders 集合有以下记录:
[
{"_id":4,"book":"novel 1","price":300,"quantity":20},
{"_id":5,"book":"science 1","price":20,"quantity":1}
]
books 集合有以下记录:
[
{"_id":"book1","author":"author 1","category":"novel","stock":10,"time":1564456048486,"title":"novel 1"},
{"_id":"book3","author":"author 3","category":"science","stock":30,"title":"science 1"}
]
以下操作连接 orders 和 books 集合,要求两个条件:
orders 的 book 字段与 books 的 title 字段相等
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))
在上述示例代码片段中, 在 .match(_.expr(.... 这段标红的代码处,未定义变量 _;
示例代码片段中的 _.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))