首页 > 解决方案 > 如何从 Mongoose Graphql 的一对一关系的反向模型中获取数据?

问题描述

如何从 GraphQl 一对一关系中获取反向模型数据?

当我尝试通过用户模型获取客户数据时,它返回客户 null

**1. user schema**
=========================

const userSchema = mongoose.Schema({      
      username: {
          type: String,
          required: false,
      },
    });



**2.customer schema**
=========================

const customerSchema = mongoose.Schema({
  address:{
    type:String,
    require:false,
  },
  userId:{
    type:mongoose.Types.ObjectId,
    require:true,
  },
});

GraphQl 模式

const CustomerType = new GraphQLObjectType({
  name: 'Customer',
  fields:()=>({
    id:{
      type:GraphQLID
    },
    address:{
      type:GraphQLString
    }, 
    userId:{
      type:GraphQLString
    }, 
    user:{
      type:UserType,
      resolve(parent,args){
        return User.findById(parent.userId)
      }      
    }
  })
});

//---------------------------------------------  
  //User Type....
//----------------------------------------------  

const UserType = new GraphQLObjectType({
  name: 'User',
  fields:()=>({
    id:{
      type:GraphQLID
    },
  
    username:{
      type:GraphQLString
    },
    customer:{
      type:CustomerType,
      resolve(parent,args){
        return Customer.findById(parent.id)
      }      
    }

  })
});

我的 GraphQl 查询是

query{
  user(id:"613c8f2c58439637cf43394e"){
    id
    username
    customer{
      id
    }
  }
}


Result:
=========================
{
  "data": {
    "user": {
      "id": "613c8f2c58439637cf43394e",
      "username": "Ahmed sohel",
      "customer": {
        "id": null
      }
    }
  }
}

它的虚拟随机虚拟文本内容用于增加描述然后编码。请不要在此行之后阅读..

什么是 Lorem Ipsum?Lorem Ipsum 只是印刷和排版行业的虚拟文本。自 1500 年代以来,Lorem Ipsum 一直是行业的标准虚拟文本,当时一位不知名的印刷商采用了一种类型的厨房并将其加扰以制作一本类型样本书。它不仅经历了五个世纪,而且经历了电子排版的飞跃,基本保持不变。它在 1960 年代随着包含 Lorem Ipsum 段落的 Letraset 表的发布而流行起来,最近还随着 Aldus PageMaker 等桌面出版软件(包括 Lorem Ipsum 的版本)而普及。

我们为什么用它?一个早已确立的事实是,读者在查看页面布局时会被页面的可读内容分散注意力。使用 Lorem Ipsum 的重点在于它具有或多或少的正态分布字母,而不是使用“这里的内容,这里的内容”,使它看起来像可读的英语。许多桌面出版包和网页编辑器现在使用 Lorem Ipsum 作为他们的默认模型文本,搜索“lorem ipsum”会发现许多 w

标签: node.jsmongoosefacebook-graph-apigraphql

解决方案


推荐阅读