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

时间:2019-08-26 23:14:51

标签: javascript node.js mongodb mongoose 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!
    }

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

所以我应该在我的预订解析器中填充“用户”?

要解决我所做的用户

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

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

2 个答案:

答案 0 :(得分:1)

在保存新的Booking之后,我从未做过这样的事情:

const result = await booking.save();

您可以在result上使用.populate()。示例:

await result.populate("user");

或者如果以上方法无效:

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

答案 1 :(得分:1)

希望对您有帮助。

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