我正在使用 Graphql,然后遇到需要填充的情况,但我不知道如何执行它。
这是我的预订架构
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)
这是我创建预订事件的解析器
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 查询时,我很容易得到我需要的东西
mutation{
bookevent(eventid:"5d6465b4ef2a79384654a5f9"){
_id
}
}
gives me
{
"data": {
"bookevent": {
"_id": "5d64672440b5f9387e8f7b8f"
}
}
但现在我如何在这里填充用户???
因为最后我希望这个查询能够成功执行
mutation{
bookevent(eventid:"5d6465b4ef2a79384654a5f9"){
_id
user{
email
}
}
eventtype 的架构是
type Event{
_id:ID!
title:String!
description:String!
price:Float!
date:String!
creator: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方法对吗?