【发布时间】:2020-08-18 08:19:38
【问题描述】:
如果某些条件评估为真或假,有什么方法可以省略 MongoDB 聚合阶段之一?
我正在构建餐厅搜索器应用程序,您可以在其中按名称、他们提供的美食等查找餐厅。用户可以输入的字段之一是餐厅 name 字段。如果用户将其留空,我不想在名称字段上执行 $text 搜索,但我不知道如何实现。
这是我的示例代码,但是它不起作用,因为它会触发警报 MongoError: unknown top level operator: $cond。
const { borough, cuisine, name } = req.body;
try {
const restaurantCollection = databaseFunctions
.getDatabase()
.collection('restaurants');
const fetchedRestaurants = await restaurantCollection
.aggregate([
{
$match: {
$and: [
{
$cond: {
if: { $ne: [name, ''] },
then: { $text: { $search: name } },
else: null,
},
},
{ borough: { $in: borough } },
{ cuisine: { $in: cuisine } },
],
},
}]
} catch {...}
我怎样才能实现它?
【问题讨论】: