Populating the “Ref” in mongoose schema while work

2020-04-10 01:03发布

问题:

Hey guys 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

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

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" ??

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 ?

回答1:

I hope it may help you.

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


回答2:

I have never made anything like this before but after saving new Booking here:

const result = await booking.save();

You can use .populate() on result. Example:

await result.populate("user");

Or if the above not work:

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