簡體   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