Mongodb:在另一个集合中查找,如果在第一个集合中找不到数据

时间:2020-04-17 16:04:19

标签: node.js mongodb mongoose aggregation-framework

我想从2个集合中的任何一个中查找数据。如果在第一个集合中找不到数据,则必须查看第二个集合。

我尝试将$ lookup与聚合管道一起使用,但是在某种情况下,它在当前情况下不起作用。

我在这里使用猫鼬(4.10.8版)

我有 DestinationPage 作为一个集合,在这里我找到与 destinationPage_name 匹配的文档,如果我没有得到数据(如果返回的话,将返回null),然后我希望在与 specialityPage_name 匹配的 SpecialityPage 集合中找到它。

 DestinationPage.aggregate([
        { "$match" : { "destinationPage_name": { $regex: SEARCH_REF_DESTINATION, $options: 'i' } }},
        { "$lookup" : {
            "from" : "SpecialityPage",
            "localField" : "specialityPage_name",
            "foreignField" : { $regex: SEARCH_REF_DESTINATION, $options: 'i' },
            "as" : "data2"
          }
        },

      ]).then(doc => {
        console.log('document', doc);
      })
      .catch(err => {
        console.error("got error : ", err);
      })

上面的代码给出错误,

"The 'cursor' option is required, except for aggregate with the explain argument"

如果我添加{ cursor:{} },甚至连控制台打印都看不到。

选项: 我可以检查一个集合中的数据,如果没有任何数据,那么在回调中,我可以检查另一个集合。但是我不认为这是一种有效的方法。

谢谢。

“#stayhomestaysafe”

1 个答案:

答案 0 :(得分:0)

您的猫鼬版本与MongoDB v4.10.8不兼容。

您需要升级到最新版本v5.9.9

MongoDB Server Version Compatibility

相关问题