簡體   English   中英

Mongo $ lookup返回空數組

[英]Mongo $lookup return empty array

在架構上執行$ lookup時,它總是返回一個空數組。 我究竟做錯了什么?

結果收集

const resultSchema = new mongoose.Schema({
  trial: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Trial',
    required: true
  }
});

試用集

const trialSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
});

骨料

Result.aggregate([
    {
      $lookup: {
        from: 'trial',
        localField: 'trial',
        foreignField: '_id',
        as: 'x'
      }
    }
  ])
    .exec()
    .then(results => ({ results }))

最后,“ x”最終始終是一個空數組。

好的,就在這里找到答案: https : //stackoverflow.com/a/45481516/3415561

查找中的“來自”字段必須是您的集合名稱,而不是模型名稱。 因此,它是一個復數詞。 這是

from: 'trials'

代替

from: 'trial'

檢查集合名稱。 在匯總函數“試用”中以小寫開頭,在結果集合中“試用”以大寫開頭

在我的情況下,我錯誤地在集合名稱的前面加上了$:

{$lookup: {
  from: '$users', // <- incorrect
  foreignField: '_id',
  localField: 'userid',
  as: 'users'
}},

它必須是

{$lookup: {
  from: 'users', // <- correct
  foreignField: '_id',
  localField: 'userid',
  as: 'users'
}},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM