有条件地排除在 MongoDB 中不起作用的字段

Conditionally excluding field not working in MongoDB

我想从数据库中获取一个用户。我的函数接受一个 requesterId ,它是请求此数据的用户的 ID,以及一个 targetId 这是要检索的用户。

如果请求者在目标的 friends 数组(字符串)中,则 phone 字段应包含在投影中。如果不是,则排除。

阅读示例 here 后,我提出了以下查询。但是,无论如何,phone 字段总是 returned。我做错了什么?

  getUser: function getUser(requesterId, targetId) {
    return db.collection('users').aggregate([
      {$match: {userId: targetId}},
      {
        $project:
          {
            firstName: 1,
            phone: {
              $cond: {
                if: {friends: requesterId},
                then: "$phone",
                else: "$$REMOVE"
              }
            }
          }
      },
      {$limit: 1}
    ]).toArray();
  }

Schema(在 Compass 中创建,因此没有代码):
userId - 字符串
firstName - 字符串
friends - 数组(字符串)
phone - 字符串

指数None 在此合集中

例子:

/* Bob's MongoDB data */ {userId: "BobID", firstName: "Bob", friends: ["AmyID"], phone: "1234567890"}
getUser(requesterId = 'AmyID', targetId = 'BobID');
/* Result */ {firstName: "Bob", phone: "1234567890"}

/* Amy's MongoDB data */ {userId: "AmyID", firstName: "Amy", friends: ["CassieID"], phone: "9876543210"}
getUser(requesterId = 'BobID', targetId = 'AmyID');
/* Result */ {firstName: "Amy", phone: "987654321"}

Bob 请求 Amy 的用户不应该 return 她的 phone 号码,因为他不在她的 friends 数组中。

if: 值必须是布尔表达式,而不是查询对象。要检查指定值是否在数组中,可以使用 $in 表达式:

db.collection('users').aggregate([
  {$match: {userId: targetId}},
  {
    $project:
      {
        firstName: 1,
        phone: {
          $cond: {
            if: {$in: [requesterId, '$friends']},
            then: "$phone",
            else: "$$REMOVE"
          }
        }
      }
  },
  {$limit: 1}
])