如何进行更新变异 - GraphQL(加上mongoDB)

时间:2018-01-25 05:44:37

标签: node.js mongodb express mongoose graphql

我想对相册进行更新变更,但是我在获取更新和获取返回值时遇到问题。

Schema Mongoose:

var AlbumSchema = new Schema({
    name: String,
    dateCreated: { type: Date, default: Date.now },
    dateUpdated: { type: Date, default: Date.now }
});

GraphQL类型:

    const AlbumType = new GraphQLObjectType({
        name: 'Album',
        fields: () => ({
            id: {type:GraphQLID},
            name: {type:GraphQLString},
            dateCreated: {type: GraphQLString},
            dateUpdated: {type: GraphQLString}
        })
    })

更新变异:

updateAlbum: { //STILL TRYING TO GET TO WORK
            type: AlbumType,
            args: {
                id: {type: new GraphQLNonNull(GraphQLString)},
                name: {type: new GraphQLNonNull(GraphQLString)}
            },
            resolve(parentValue, args){
                return new Promise((resolve, reject) => {
                    ALBUM.findOneAndUpdate(
                        {id: args.id},
                        {name: args.name},
                        //{dateUpdated:  Date.now()}
                    ).exec((err, res) => {
                        if(err) reject(err)
                        else resolve()
                    })
                })
            }
        }

测试突变:

mutation {
  updateAlbum(id:"5a695c586c050802f182270c", name: "album 333"){
    id
   name }}

测试突变的响应:

{
  "data": {
    "updateAlbum": null
  }
}

问题:

  1. 我应该如何编写updateAlbum函数?

  2. (不太重要)如何添加Date.now()以获取新的dateUpdated:值?

  3. 如何获得返回值或者我能得到的回复是updateAlbum: null?谢谢!

1 个答案:

答案 0 :(得分:0)

  1. 见下文。您需要添加“$ set”来放置您将要更改的参数集。

    updateAlbum: { type: AlbumType, args: { id: {type: new GraphQLNonNull(GraphQLString)}, name: {type: new GraphQLNonNull(GraphQLString)} }, resolve(parentValue, args){ return new Promise((resolve, reject) => { const date = Date().toString() ALBUM.findOneAndUpdate( {"_id": args.id}, { "$set":{name: args.name, dateUpdated: date}}, {"new": true} //returns new document ).exec((err, res) => { console.log('test', res) if(err) reject(err) else resolve(res) }) }) } }

  2. 日期需要变成一个字符串,与Date()而不是Date.now()一起保留,与mongoose格式保持一致。

  3. 见上文,您需要将res添加到resolve()