簡體   English   中英

如何在 mongoose 的子文檔數組中查找字段?

[英]How to lookup a field in an array of subdocuments in mongoose?

我有一系列這樣的評論對象:

   "reviews": {
        "author": "5e9167c5303a530023bcae42",
        "rate": 5,
        "spoiler": false,
        "content": "This is a comment This is a comment This is a comment.",
        "createdAt": "2020-04-12T16:08:34.966Z",
        "updatedAt": "2020-04-12T16:08:34.966Z"
    },

我想要實現的是查找作者字段並獲取用戶數據,但問題是我嘗試使用的查找只返回給我:

代碼:

 .lookup({
    from: 'users',
    localField: 'reviews.author',
    foreignField: '_id',
    as: 'reviews.author',
  })

回復:

api的響應

有什么方法可以獲取作者在該領域的數據? 這就是作者的身份。

嘗試在您的數據庫上執行以下查詢:

db.reviews.aggregate([
  /** unwind in general is not needed for `$lookup` for if you wanted to match lookup result with specific elem in array is needed */
  {
    $unwind: { path: "$reviews", preserveNullAndEmptyArrays: true },
  },
  {
    $lookup: {
      from: "users",
      localField: "reviews.author",
      foreignField: "_id",
      as: "author", // Pull lookup result into 'author' field
    },
  },
  /** Update 'reviews.author' field in 'reviews' object by checking if   'author' field got a match from 'users' collection.
   * If Yes - As lookup returns an array get first elem & assign(As there will be only one element returned -uniques),
   * If No - keep 'reviews.author' as is */
  {
    $addFields: {
      "reviews.author": {
        $cond: [
          { $ne: ["$author", []] },
          { $arrayElemAt: ["$author", 0] },
          "$reviews.author",
        ],
      },
    },
  },
  /** Group back the documents based on '_id' field & push back all individual 'reviews' objects to 'reviews' array */
  {
    $group: {
      _id: "$_id",
      reviews: { $push: "$reviews" },
    },
  },
]);

測試: MongoDB-Playground

注意:以防萬一您在文檔中有其他字段以及需要保留在 output 中的reviews ,然后從$group開始使用這些階段:

  {
    $group: {
      _id: "$_id",
      data: {
        $first: "$$ROOT"
      },
      reviews: {
        $push: "$reviews"
      }
    }
  },
  {
    $addFields: {
      "data.reviews": "$reviews"
    }
  },
  {
    $project: {
      "data.author": 0
    }
  },
  {
    $replaceRoot: {
      newRoot: "$data"
    }
  }

測試: MongoDB-Playground

注意:嘗試保持查詢在較小的數據集上運行,可能通過添加$match作為第一階段來過濾文檔並具有適當的索引。

您應該在對服務器的請求中使用 mongoose populate('author')方法,該服務器獲取該作者的 id 並將用戶數據添加到 mongoose 的響應中,並且不要忘記以這兩個 Z0B9ABFE67CC31FCF16Z 的方式設置您的架構在您的評論架構中連接,您應該將 ref 添加到作者用戶保存的架構作者:{ type: Schema.Types.ObjectId, ref: 'users' },

您可以按照此代碼

$lookup:{
            from:'users',
            localField:'reviews.author',
            foreignField:'_id',
            as:'reviews.author'
        }
**OR**

> When You find the doc then use populate
> reviews.find().populate("author")


暫無
暫無

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

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