graphql中的查询

时间:2019-04-30 22:24:37

标签: mongodb graphql

我正在尝试使用graphql进行查询,以获取按ID查找一个用户的朋友列表。

我的Mongodb是以下各项的多个集合:

{
  "_id": ObjectId("5c09af1ebaa7a16d74d52494"),
  "name": "zaraza",
  "surname": "zaraza",
  "email": "zaraza@gamil.com",
  "state": "Disponible",
  "__v": 0,
  "avatar": "https://cdn.iconscout.com/icon/free/png-256/avatar-380-456332.png",
  "ip": "",
  "friends": [
    {
      "_id": "5c09af05baa7a16d74d52493"
    },
    {
      "_id": "5c09af32baa7a16d74d52495"
    },
    {
      "_id": "5c09af45baa7a16d74d52496"
    },
    {
      "_id": "5c09afda583b656e6d350dd5"
    }
  ]
}

我的graphql查询是:

query {
  singleUser(
    _id: "5c09afda583b656e6d350dd5"
  ){
    _id
    name
    surname
    email
    state
    avatar
    friends{
      _id
    }
    }
}

但是我不知道如何查询“朋友”数组的_id来用每个_id朋友的名字来完成我的结果

我得到的最后一个代码是:

{
  "data": {
    "singleUser": {
      "_id": "5c09afda583b656e6d350dd5",
      "name": "zaraza",
      "surname": "zaraza",
      "email": "zaraza@gamil.com",
      "state": "Disponible",
      "avatar": "https://cdn.iconscout.com/icon/free/png-256/avatar-373-456325.png",
      "friends": [
        {
          "_id": "5c09af32baa7a16d74d52495"
        },
        {
          "_id": "5c09af45baa7a16d74d52496"
        },
        {
          "_id": "5c09afda583b656e6d350dd5"
        }
      ]
    }
  }
}

但是我想得到:

{
  "data": {
    "singleUser": {
      "_id": "5c09afda583b656e6d350dd5",
      "name": "zaraza",
      "surname": "zaraza",
      "email": "zaraza@gamil.com",
      "state": "Disponible",
      "avatar": "https://cdn.iconscout.com/icon/free/png-256/avatar-373-456325.png",
      "friends": [
        {
          "_id": "5c09af32baa7a16d74d52495"
          **"name": "zaraza2"**
        },
        {
          "_id": "5c09af45baa7a16d74d52496"
          **"name": "zaraza3"**
        },
        {
          "_id": "5c09afda583b656e6d350dd5"
          **"name": "zaraza4"**
        }
      ]
    }
  }
}

字段名称位于同一集合中

1 个答案:

答案 0 :(得分:0)

resolver中,您可以定义函数来解析特定字段。

我们将在User Type上定义一个函数来解析friends字段。

const resolver = {
  // This is the type
  User: {
    // when we query friends field on the User type, run this function
    // first argument is the parent doc which we will use to 
    // extract the friends ids
    friends: parent => User.find({ _id: { $in: parent.friends } }, { name: 1 }) 
  }
};