Express, GraphQL, and MongoDB use and access data

EXpress

​ With the foundation of node.js, you can easily get started with express. Express is a simple and flexible web application framework for node.js. Its core features are as follows:

  • Multiple middleware can be set to respond to http requests and handle interfaces
  • Defines the routing table used to perform different HTTP request actions
  • HTML pages can be rendered dynamically by passing parameters to the template
  • Supports server-side rendering and client-side rendering

Need to have the foundation of node.js, understand middleware, static resource configuration, etc. and core concepts.

GraphQL

GraphQL is a database query language, an alternative to rest APIs.

​ It is not only a query language for API but also a runtime that satisfies query data. GraphQL provides a complete set of understanding-based descriptions for API data, enabling clients to accurately obtain the data they need without any redundancy , and also make it easier for the API to evolve over time.

Features:

  • Get multiple resources with only one request
  • Describe all similar systems, easy to maintain, smooth progress according to needs, add or hide fields

Differences from the Restful interface:

  • A restful interface can only return one resource, while GraphQL can obtain multiple resources at one time
  • Restful uses different urls to distinguish resources, while FraphQL uses types to distinguish resources

type:

  • Query : query
  • Mutation: operation/modification

MongoDB

​ MongoD is a database based on distributed file storage. It is between relational databases and non-relational databases. It is the most similar to relational databases in non-relational databases. It supports a very loose data structure and is similar to json in bson format. Therefore, it can store more complex data types. The biggest feature of Mongo is that the query language it supports is very powerful. Its syntax is similar to object-oriented query language. It can almost realize most of the functions similar to relational database form query, and it supports database Build an index.

Features:

  • high performance
  • easy to deploy
  • easy to use

The method of configuring MongoDB is as follows. I won’t go into details here. It is recommended to install a visualization tool after installation, otherwise it is not easy to observe the database status.

Use express to use graphql to access mongodb operation data

Environment (the version must match):

node -v   //v16.20.1
 "dependencies": {
    
    
    "express": "^4.16.4",
    "express-graphql": "^0.7.1",
    "graphql": "^14.0.2",
    "mongoose": "^6.5.0"
  }

​Note : The version of node must match the version of graphql and mongoose, otherwise the follow-up cannot be performed

​ The version of node should not be too high. I used version 18.x at the beginning, and later found that it did not match mongoose, so I started to downgrade node to 16.20

configuration

​ After installing MongoDB, run net start MongoDB as an administrator, start the database, and open localhost: 27017. If you can access it successfully, it means that the mongodb service has been successfully started.

After installing the above versions, create a new js file:

const express = require('express') 
const {
    
     buildSchema} = require('graphql') 
const graphqlHttp = require('express-graphql')

// 连接数据库服务
const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/test")

//设置Schema
const schema = buildSchema(`
    type Person{
        name: String,
        age: Int,
        id: String
    }
    type Query{
        getList: [Person],
        hello:String
    }
    input TempInput{
        name: String,
        age: Int,
    }
    type Mutation{
        createPerson(input: TempInput):Person,
        updatePerson(id:String!,input:TempInput):Person,
        deletePerson(id: String!): Int
    }
`)

//定义模型: 限制数据库films集合的只能存几个字段
var PersonModel = mongoose.model('person',new mongoose.Schema({
    
    
    name: String,
    age: Number
}))
const root = {
    
    
    createPerson({
     
     input}){
    
    
       return  PersonModel.create({
    
    ...input})
    },
    getList(){
    
    
        return PersonModel.find()
        // return 'getList'
    },
    hello(){
    
    
        return 'hello'
    },
    updatePerson({
     
     id,input}){
    
    
        return PersonModel.updateOne({
    
    
            _id: id
        },{
    
    
            ...input
        }).then(res => PersonModel.find({
    
    _id: id})).then(res =>{
    
    
            return res[0]
        })
    },
    deletePerson({
     
     id}){
    
    
        return PersonModel.deleteOne({
    
    _id: id}).then(res => 1)
    }
}
const app = express()
app.use('/graphql',graphqlHttp({
    
    
    rootValue: root,
    schema: schema,
    graphiql: true // 表示启用graphql调试
}))
//配置静态资源目录
app.use(express.static("public"))

app.listen(3000)// 链接数据库服务,后续前端访问时一定注意跨域问题
const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/test")

​ Because the above file is a js file, it needs to be run with node when running, but it will be invalidated when the code is changed. You can install nodemon or dev-sever to run. Here I installed nodemon. The installation command is as follows: (note that it must be installed globally)

npm i nodemon -g

start up:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-KFR6xmQj-1691236320223) (C:\Users\Changjing\AppData\Roaming\Typora\typora-user-images \image-20230805134217217.png)]

After startup, you can go to localhost:3000/graphql to access and debug the interface.

We create a new temporary html file. Since express supports static resource access, visit: localhost: 3000/html test interface Use the fetch interface to test the above interface:

Note that we are using fetch, which requires two consecutive chain calls to get the real data in the second chain call

graphql uses the post interface. If you use axios or Xhr to call, you must remember that the method is post

Another: The template string of the query must be written strictly according to the definition of the backend, and if there is one less!, an error will be reported, so be sure to pay attention.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Home</h1>
    <button onclick="getData()">查询数据</button>
    <button onclick="createData()">创建数据</button>
    <button onclick="updateData()">更新数据</button>
    <button onclick="deleteData()">删除数据</button>

    <script>
        function getData(){
      
      
            const myQuery = `
                query{
                    getList{
                        name,
                        id,
                        age
                    }
                }
            `
            fetch("/graphql",{
      
      
                method:'POST',
                headers:{
      
      
                    "Content-Type":"application/json",
                    "Accept":"application/json"
                },
                body:JSON.stringify({
      
      
                    query: myQuery
                })
            }).then(res => res.json()).then(res => {
      
      
                console.log(res)
            })
        }
        function createData(){
      
      
            // mutation($input:TempInput) 对标后端的类型
            // $input: 表示该值是可变的
            const myQuery = `
             mutation($input:TempInput){
                 createPerson(input: $input){
                    id,
                    name,
                    age
                 }
             }
            `
            fetch("/graphql",{
      
      
                method:'POST',
                headers:{
      
      
                    "Content-Type":"application/json",
                    "Accept":"application/json"
                },
                body:JSON.stringify({
      
      
                    query: myQuery,
                    variables:{
      
      
                        input:{
      
      
                            name:"牡丹",
                            age: 11,
                        }
                    }
                })
            }).then(res => res.json()).then(res => {
      
      
                console.log(res)
            })
        }
        function updateData(){
      
      
            const myQuery = `
             mutation($id: String!,$input:TempInput){
                  updatePerson(id: $id,input: $input){
                    id,
                    name,
                    age
                 }
             }
            `
            fetch("/graphql",{
      
      
                method:'POST',
                headers:{
      
      
                    "Content-Type":"application/json",
                    "Accept":"application/json"
                },
                body:JSON.stringify({
      
      
                    query: myQuery,
                    variables:{
      
      
                        id:"64cd090d9862f157708ee186",
                        input:{
      
      
                            name:"百合",
                            age: 11,
                        }
                    }
                })
            }).then(res => res.json()).then(res => {
      
      
                console.log(res)
            })
        }
        function deleteData(){
      
      
            const myQuery = `
             mutation($id: String!){
                  deletePerson(id: $id)
             }
            `
            fetch("/graphql",{
      
      
                method:'POST',
                headers:{
      
      
                    "Content-Type":"application/json",
                    "Accept":"application/json"
                },
                body:JSON.stringify({
      
      
                    query: myQuery,
                    variables:{
      
      
                        id:"64cd090d9862f157708ee186",
                    }
                })
            }).then(res => res.json()).then(res => {
      
      
                console.log(res)
            })
        }
    </script>
</body>
</html>

result:

After the query interface is called:

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-lw8egjrJ-1691236320224) (C:\Users\Changjing\AppData\Roaming\Typora\typora-user-images \image-20230805135847215.png)]

After making the modification, we use the studio3 visualization tool to look at the data in the table:

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-NxdTKrbs-1691236320224) (C:\Users\Changjing\AppData\Roaming\Typora\typora-user-images \image-20230805140101528.png)]

It will automatically generate a string type _id, which is convenient for identification storage.

The next section records how to operate in combination with react.

Guess you like

Origin blog.csdn.net/weixin_44813858/article/details/132123886