Mongoose - 有条件地更新更新查询中的字段

问题描述 投票:0回答:1

我有以下查询,它从文档中的两个数组(请求和关注者)中提取

id

User.updateOne(
    { _id: otherUserId },
    { $pull: { requests: userId, followers: userId } }
)

我想通过使用一个条件来修改此查询,该条件说明

userId
是否在
requests
数组中,然后从
requests
中提取,但不更新关注者数组。如果
id
不在
requests
中,则从
followers
拉出。目前,这两个字段都会更新。有什么方法可以使用一个查询来完成此任务吗?

我尝试了以下代码,但它返回了

CastError

User.updateOne(
    { _id: otherUserId },
    { $pull: { requests: userId, followers: {$nin: [new mongoose.Types.ObjectId(userId), "$requests"]} }}
)
mongodb mongoose mongodb-update
1个回答
2
投票

聚合管道应该能够实现它。

requests

  • $filter
    - 过滤
    requests
    数组以删除
    userId
    (如果存在)。

followers

  • $cond
    - 检查
    userId
    不在
    requests
    数组中。
  • 如果
    true
    ,则从
    userId
    数组中删除
    followers
  • 否则,保留
    followers
    数组。
User.updateOne(
{ _id: otherUserId },
[
  {
    $set: {
      requests: {
        $filter: {
          input: "$requests",
          cond: {
            $ne: [
              "$$this",
              userId
            ]
          }
        }
      },
      followers: {
        $cond: {
          if: {
            $not: {
              $in: [
                userId,
                "$requests"
              ]
            }
          },
          then: {
            $filter: {
              input: "$followers",
              cond: {
                $ne: [
                  "$$this",
                  userId
                ]
              }
            }
          },
          else: "$followers"
        }
      }
    }
  }
])

演示@Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.