簡體   English   中英

如何進行更新變異 - GraphQL(加上 mongoDB)

[英]How to make Update Mutation - GraphQL (plus mongoDB)

我想對專輯進行更新突變,但在獲取更新和獲取返回值時遇到問題。

模式貓鼬:

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. 見下文。 您需要添加“$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)
                        })
                    })
                }
            }
  1. 日期需要做成字符串,用 Date() 而不是 Date.now() 保持與 mongoose 格式相同。
  2. 見上,需要在resolve()添加res

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM