简体   繁体   English

在使用 Graphql 时填充猫鼬模式中的“Ref”

[英]Populating the "Ref" in mongoose schema while working with Graphql

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.我正在使用 Graphql,然后我遇到了需要填充的情况,但我不知道如何执行。

Here is my Booking schema这是我的预订模式

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()
    };
  }
};

When i try to run the graphql query i easily get what i require当我尝试运行 graphql 查询时,我很容易得到我需要的

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

gives me给我

{
  "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
    }
  }

Schema of eventtype is事件类型的架构是

  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" ??那么我应该在我的 Booking 解析器中的哪个位置填充“用户”?

To resolve the user I did为了解决我所做的用户

 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)

I have never made anything like this before but after saving new Booking here:我以前从未做过这样的事情,但在此处保存新Booking后:

const result = await booking.save();

You can use.populate() on result .您可以在result上使用.populate() Example:例子:

await result.populate("user");

Or if the above not work:或者,如果上述方法不起作用:

await result.populate("user").execPopulate();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM