简体   繁体   中英

how to return new record from graphql mutation instead of null

I read through the apollo-server-tutorial and I'm trying to replicate it with only mongodb - no sqllite. I'm coming from meteor so I'm learning async & mongoose while I'm at it.

My mutation for addAuthor() works correctly (I see a new record in the DB) but graphiql returns null. How do I get it to return the expected fields?

mutation {
  addAuthor(firstName: "falieson", lastName:"p") {
    _id
    firstName
    lastName
  }
}

{
  "data": {
    "addAuthor": null
  }
}

Schema: https://github.com/Falieson/apollo-server-tutorial-only-mongodb/blob/master/data/schema.js#L39

Resolver: https://github.com/Falieson/apollo-server-tutorial-only-mongodb/blob/master/data/resolvers.js#L38

Mongoose: https://github.com/Falieson/apollo-server-tutorial-only-mongodb/blob/master/data/models/mongoose.js#L51

Model: https://github.com/Falieson/apollo-server-tutorial-only-mongodb/blob/master/data/models/index.js#L7

I needed to have mongoose return a promise for the mutation. So my MongooseModel.create() changes from

const record = new this.collection(args)
return record.save(cb)

to using Promise

const record = new this.collection(args)
return new Promise((resolve, reject) => {
   record.save((err, res) => {
      err ? reject(err): resolve(res)
   });
});

to using Async/Await

 async create(obj = {}) {
   const args = {
     ...this.defaultRecord(),
     ...obj
   }
   const record = new this.Collection(args)

   try {
     const savedRecord = await record.save()
     return savedRecord
   } catch (err) {
     handleError(err)
   }
 }

My mutation doesn't have to change at all, but my fixtures generator also has to be updated to use the Promise.then() chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM