使用 graphql 和 nodejs 填充猫鼬模式

Populating mongoose schema with graphql and nodejs

大家好,我在这里使用 graphql 和 mongoose 以及 nodejs,所以我的模式是这样的

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:
      'alNyWl8w9gWLo8TtJDL2Te6Wg6psQOrOveinifFF4Jjeij9b4P2Ga',
     __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 是我在解析器中返回的事件,但事件标题为空, 即使我试过了

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

  }
}

它说

cannot query field title on type Booking

那么我如何获取与刚刚删除的预订关联的事件的标题?

如果要cancelEvent到returnBooking,那么这个突变就已经正确了

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

但是在你的解析器中你必须 return booking 而不是 event.

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

否则如果你想returnevent那么你必须将cancelEvent突变的类型更改为Event

在那种情况下你可以使用这个突变

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

使用以下解析器

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