繁体   English   中英

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

[英]Mongodb: Find in another collection, if data not found in first collection

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

我尝试将 $lookup 与聚合管道一起使用,但不知何故,它在目前的情况下不起作用。

我在这里使用 Mongoose(版本 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'

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

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

MongoDB服务器版本兼容性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM