[英]Populating the "Ref" in mongoose schema while working with Graphql
我正在使用 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
}
}
给我
{
"data": {
"bookevent": {
"_id": "5d64672440b5f9387e8f7b8f"
}
}
但现在我如何在这里填充用户???
因为最后我希望这个查询成功执行
mutation{
bookevent(eventid:"5d6465b4ef2a79384654a5f9"){
_id
user{
email
}
}
事件类型的架构是
type Event{
_id:ID!
title:String!
description:String!
price:Float!
date:String!
creator:User!
}
因为我的用户架构中有电子邮件,我正在尝试将其发送出去
那么我应该在我的 Booking 解析器中的哪个位置填充“用户”?
为了解决我所做的用户
const result = await booking.save();
const res=await result.populate("user");
console.log(res) //doesnt gives the populated user only gives me id
如果我对这些情况没有错,填充方法对吗?
我希望它可以帮助你。
const result = await booking.save();
const res=await booking.findById(result._id).populate("user");
console.log(res)
我以前从未做过这样的事情,但在此处保存新Booking
后:
const result = await booking.save();
您可以在result
上使用.populate() 。 例子:
await result.populate("user");
或者,如果上述方法不起作用:
await result.populate("user").execPopulate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.