填充“Ref"使用 Graphql 时在猫鼬模式中 [英] Populating the "Ref" in mongoose schema while working with Graphql
问题描述
我正在使用 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.
这是我的预订模式
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
如果我对这些情况没有错 populate 是正确的方式吗?
If I am not wrong for these cases populate is the way right?
推荐答案
希望能帮到你.
const result = await booking.save();
const res=await booking.findById(result._id).populate("user");
console.log(res)
这篇关于填充“Ref"使用 Graphql 时在猫鼬模式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!