如何在猫鼬的子文档数组中查找字段?

时间:2020-04-12 19:56:06

标签: mongodb mongoose mongodb-query aggregation-framework mongoose-populate

我有很多这样的评论对象:

   "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"
    },

我想要实现的是查找 author 字段并获取用户数据,但是问题是我尝试使用的查找仅将其返回给我:

代码:

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

响应:

Response of api

有什么方法可以获取作者在该字段中的数据?那就是作者的ID。

3 个答案:

答案 0 :(得分:1)

尝试对您的数据库执行以下查询:

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

注意::以防万一,如果文档中还有其他字段需要与reviews一起保留在输出中,则从$group开始,请使用以下阶段: / p>

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

测试: MongoDB-Playground

注意:可能要保持查询在较小的数据集上运行,可以通过添加$match作为过滤文档的第一阶段并具有适当的索引。

答案 1 :(得分:0)

您应该在对服务器的请求中使用猫鼬的populate('author')方法,该服务器获取该作者的ID并将用户数据添加到猫鼬的响应中 并且不要忘记以连接这两个集合的方式来设置架构 在您的审阅模式中,应该将引用添加到保存作者用户的模式中 作者:{类型:Schema.Types.ObjectId,参考:“用户”},

答案 2 :(得分:0)

您可以遵循以下代码

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

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