.Net6 + GraphQL + MongoDb 实现Mutate更新数据

介绍

Query的部分我们讲完了,现在讲一下Mutate(就是操作增修删) 本节讲一下修改,删除就不讲了

正文

    public record UpdatePostInput(string PostId,string Title, string Author);   


    public record UpdatePostPayload(Post Post);

新增函数

        public async Task<UpdatePostPayload> UpdatePostAsync(
            [Service] DbContext db,
            UpdatePostInput input)
        {

            var _cbf = Builders<Post>.Filter
                .Eq(restaurant => restaurant.Id, input.PostId);


            var _cbu = Builders<Post>.Update
                .Set(restaurant => restaurant.Title, input.Title)
                .Set(restaurant => restaurant.Author, input.Author);

            _ = await db.Post.UpdateOneAsync(_cbf, _cbu);

            return new UpdatePostPayload(await db.Post.Find(x => x.Id == input.PostId).FirstOrDefaultAsync());


        }

这时候我们去https://localhost:7145/graphql/调用接口

query testGetBookByTitle {
  posts {
    items {
      id
      title
      author
      comments {
        name
      }
    }
  }
}

# 63e736ba01210efaee01a764

mutation updatePost {
  updatePost(input: { title:"11 aa", author:" au 2222", postId:"63e736ba01210efaee01a764" }) {
    post {
      title
      author
    }
  }
}

结语

本系列主要将GraphQL的使用,示例项目不能应用于生产,后续发一些GraphQL库出来讲解生产中的实际应用

联系作者:加群:867095512 @MrChuJiu

posted @ 2023-02-13 20:44  初久的私房菜  阅读(12362)  评论(0编辑  收藏  举报
作者:初久的私房菜
好好学习,天天向上
返回顶部小火箭
好友榜:
如果愿意,把你的博客地址放这里
张弛:https://blog.zhangchi.fun/