使用graphql和nodejs填充猫鼬模式

时间:2020-05-11 15:33:39

标签: node.js mongodb mongoose graphql graphql-js

伙计们,我在这里使用带猫鼬和nodejs的graphql,所以我的架构是这样的

booking.js

const mogoose = require("mongoose");
const autopopulate = require('mongoose-autopopulate')
const Schema = mogoose.Schema;
const bookingSchema = new Schema({

  event:{
    type:Schema.Types.ObjectId,
    ref:'Event',
    autopopulate:true
  },
},{timestamps:true});

module.exports=mogoose.model('Booking',bookingSchema.plugin(autopopulate))

event.js

const mogoose = require("mongoose");
const autopopulate = require('mongoose-autopopulate')
const Schema = mogoose.Schema;
const eventSchema = new Schema({
  title: {
    type: String,
  },
  description: {
    type: String,
  },
  price: {
    type: Number,
  },
  date: {
    type: String,
    required: true,
  },
  creator:{
    type:Schema.Types.ObjectId,
    ref:'User',
    autopopulate:true
  }
});

module.exports=mogoose.model('Event',eventSchema.plugin(autopopulate))

然后在我的解析器中删除我这样做的事件

cancelEvent: async (args) => {
    try {
      const booking = await Booking.findById(args.bookingID);
        const event={...booking.event,_id:booking.event._id}
       await Booking.deleteOne({ _id: args.bookingID });
       return event
    } catch (err) {
      throw err;
    }
  },

console.log(event._doc)给了我

{ _id: 5eb94b2ee627fc04777835d2,
  title: '22222',
  description: 'sd',
  date: 'df',
  creator:
   { createdEvents:
      [ [Object], [Object], [Object], [Object], [Object], [Object] ],
     _id: 5eb80367c2483e16a9e86502,
     email: 'sdd',
     password:
      '$2a$12$3lNyWl8w9gWLo8TtJDL2Te6Wg6psQOrOveinifFF4Jjeij9b4P2Ga',
     __v: 16 },
  __v: 0 }

所以可以说我的数据库就像

_id:ObjectId("5eb96b75c43aca45ff6aa934")
user:ObjectId("5eb80367c2483e16a9e86502")
event:ObjectId("5eb94b2ee627fc04777835d2")
createdAt:"2020-05-11T14:42:22.470+00:00"
updatedAt:"2020-05-11T14:42:22.470+00:00"
__v:"0"

然后我写了我的graphql查询

mutation{
  cancelEvent(bookingID:"5eb96b75c43aca45ff6aa934"){
   _id,
    event{
      title
    }  
  }
}

我回来的结果是

{
  "data": {
    "cancelEvent": {
      "_id": "5eb94b2ee627fc04777835d2",
      "event": null
    }
  }
}

id是我在解析器中返回的事件的ID,但事件标题为null, 即使我尝试过

mutation{
  cancelEvent(bookingID:"5eb96b75c43aca45ff6aa934"){
   title

  }
}

无法查询预订类型的字段标题

那么我如何获取与刚刚删除的预订相关的活动的标题?

1 个答案:

答案 0 :(得分:0)

如果您希望cancelEvent返回Booking,则此突变已经正确了

mutation {
  cancelEvent(bookingID:"5eb96b75c43aca45ff6aa934"){
   _id,
    event {
      title
    }  
  }
}

但是在您的解析器中,您必须返回booking而不是event

      const booking = await Booking.findById(args.bookingID);
      await Booking.deleteOne({ _id: args.bookingID });
      return booking

否则如果要返回event,则必须将cancelEvent突变的类型更改为Event

在这种情况下,您可以使用此突变

mutation {
  cancelEvent(bookingID:"5eb96b75c43aca45ff6aa934") {
    title
  }
}

使用以下解析器

      const booking = await Booking.findById(args.bookingID);
      await Booking.deleteOne({ _id: args.bookingID });
      return booking.event