填充"Ref"框.在使用Graphql时处于猫鼬模式 [英] Populating the "Ref" in mongoose schema while working with Graphql

查看:81
本文介绍了填充"Ref"框.在使用Graphql时处于猫鼬模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,我正在与Graphql合作,然后遇到需要填充的情况,但是我没有得到如何执行的信息

Hey guys i am working with Graphql and then i come to a situation where i need to populate, but i am not getting how to excute that

这是我的预订模式

const mongoose=require('mongoose')
const Schema=mongoose.Schema
const bookingschema=new Schema({
event:{
    type:Schema.Types.ObjectId,
    ref:'Event'
},
user:{
    type:Schema.Types.ObjectId,
    ref:'User'
}
}
,{timestamps:true})
module.exports=mongoose.model('Booking',bookingschema)

这是我创建预订活动的解析器

Here is my resolver to create a booking event

 bookevent: async args => {
    const fetchevent = await Event.findOne({ _id: args.eventid });
    const booking = new Booking({
      user: "5d64354bfd7bb826a9331948",
      event: fetchevent
    });
    const result = await booking.save();
    return {
      ...result._doc,
      _id: result._id,
      createdAt: new Date(result._doc.createdAt).toISOString(),
      updatedAt: new Date(result._doc.updatedAt).toISOString()
    };
  }
};

当我尝试运行graphql查询时,我很容易得到我所需要的

When i try to run the graphql query i easily get what i require

mutation{
  bookevent(eventid:"5d6465b4ef2a79384654a5f9"){
    _id
  }
}

给我

{
  "data": {
    "bookevent": {
      "_id": "5d64672440b5f9387e8f7b8f"
    }
  }

但是现在我该如何在此处填充用户?

but now how do i populate user here ???

由于最后我希望此查询成功执行

cause at the end i want this query to be executed successfully

mutation{
  bookevent(eventid:"5d6465b4ef2a79384654a5f9"){
    _id
    user{
      email
    }
  }

事件类型的模式为

  type Event{
        _id:ID!
        title:String!
        description:String!
        price:Float!
        date:String!
        creator:User!
    }

因为我的用户架构中包含电子邮件,所以我试图做到这一点

cause my user schema has email inside it and i am trying to reach that out

所以我应该在我的预订解析器中的哪个位置填充用户"?

So where in my Booking resolver should i populate "user" ??

要解决我做过的用户

 const result = await booking.save();
    const res=await result.populate("user");
    console.log(res) //doesnt gives the populated user only gives me id

如果在这些情况下我没错,填充是正确的方法吗?

If i am not wrong for these cases populate is the way right ?

推荐答案

我希望它可以为您提供帮助.

I hope it may help you.

const result = await booking.save();
const res=await booking.findById(result._id).populate("user");
console.log(res)

这篇关于填充"Ref"框.在使用Graphql时处于猫鼬模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆