“This is the ninth day of my participation in the First Challenge 2022. For details: First Challenge 2022”

preface

In last class, I mentioned that I wanted to directly use online Mlab to build database, but online Mlab could not be logged in normally (or it was Cloud mongodb that charged for logging in), so I had to choose local installation of mongodb for these days. This section describes how to install mongodb locally

  • Go to the official website to downloadmongodbthemsiPackage (My computer is Win10)
  • After successful installation, it will automaticallyDisk c.theProgram FilesCreate containingbinAdd the directory of the file to the system environment variabledataandlogFiles are stored inD dish)

  • At the command line terminal, entermongodHas output information, or browser address bar inputhttp://127.0.0.1:27017If the following information is displayed, the installation is successful
It looks like you are trying to access MongoDB over HTTP on the native driver port.
Copy the code

The connectionmongodb

In app.js, add the following code

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/admin') // I used the default admin database for native mongodb
mongoose.connection.once('open'.() = > {
    console.log('connected to database')})Copy the code

On the CLI, enter $nodemon Server /app.js. If the following information is displayed, the database has been successfully connected

models

We stored persons and jobs directly in memory. Now we need to store them in mongodb. In this folder, create the models folder in the root directory of the project

The code for Person.js looks like this:

const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const personSchema = new Schema({
    name: String.sex: String.age: String.jobId: String
})

module.exports = mongoose.model("Person", personSchema)
Copy the code

Module.exports = Mongoose. model(“Person”, personSchema) : Create a Collection named Person whose data structure is personSchema object

We don’t need to define an ID inside because the database automatically generates an ID for each piece of data

The code for job.js looks like this:

const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const jobSchema = new Schema({
    name: String.department: String
})

module.exports = mongoose.model("Job", jobSchema)
Copy the code

mutation

After building the models, we need to create mutation to implement add, delete and change operations on the database, which is similar to the mutation principle in VUEX. We need to modify schema.js as follows:

const Person = require('.. /models/person') const Job = require('.. /models/job') const Mutation = new GraphQLObjectType({ name: 'Mutation', fields: { addPerson: { type: PersonType, args: { name: {type: GraphQLString}, sex: {type: GraphQLString}, age: {type: GraphQLInt}}, resolve(parent, args) {// Person = new Person({name: args. Name, sex: Args.sex, age: args.age}) person.save() // This is a convenience provided by Mongoose. The instance directly calls the save method to store the data in the database specified by us}}, addJob: {type: JobType, args: { name: {type: GraphQLString}, department: {type: GraphQLString} }, resolve(parent, args) { let job = new Job({ name: args.name, department: args.department }) return job.save() } }, } }) module.exports = new GraphQLSchema({ query: RootQuery, mutation: Mutation })Copy the code

Refresh the page, http://localhost:4000/graphql, on the left side input below command and run

It is clear that the data has been successfully inserted. Why is “addPerson”: null displayed on the right? It is because we need to return data in resolve and modify the code in Resolve

resolve(parent, args) {
    let person = new Person({
        name: args.name,
        sex: args.sex,
        age: args.age
    })
    return person.save()
}
Copy the code

Run the command again, and the interface is as follows:

Execute the addJob command as follows:

associatedPersonandJob

Now we need to know the id of the Job we just inserted. I recommend installing mongodb’s graphical management tool, MongoDBCompass (provided by mongodb), to view the management data

MongoDBCompass I download zip compressed file, unzip, directly open. Exe file, connect to local database, enter admin database, you can see we just created jobs data

New person data, from the above id: 61 f0bd5de1db61c31d991977 with person association, modify the schema, js, part of the content as follows:

const Mutation = new GraphQLObjectType({
    name: 'Mutation'.fields: {
        addPerson: {
            type: PersonType,
            args: {... .jobId: {type: GraphQLID}
            },
            resolve(parent, args) {
                let person = newPerson({ ... .jobId: args.jobId
                })
                return person.save()
            }
        },
    }
})
       
Copy the code

Refresh the page and run the following command

You can view the new data on the database page

The queryPersonWhere theJob

To do this, we need to modify the Person structure as follows:

const Job = require('.. /models/job')
const PersonType = new GraphQLObjectType({
    name: 'Person'.fields: () = > ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        sex: {type: GraphQLString},
        age: {type: GraphQLInt},
        job: {
            type: JobType,
            resolve(parent, args) {
                // return _.find(jobs, {id: parent.jobId})
                // Mongoose provides model with built-in findById and find methods
                return Job.findById(parent.jobId)
            }
        }
    })
})
Copy the code

Refresh the page. Enter the following command on the left to query the result

The queryJobAll of thepersons

We need to query all the staff in a certain post. To do this, we need to reconstruct JobType, as shown below:

const JobType = new GraphQLObjectType({
    name: 'Job'.fields: () = > ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        department: {type: GraphQLString},
        persons: {
            type: new GraphQLList(PersonType),
            resolve(parent, args) {
                return Person.find({
                    jobId: parent.id
                })
            }
        }
    })
})
Copy the code

Add lisi person by mutation addPerson and associate it with jobId: “61f0bd5DE1DB61C31d991977”

The query results show that there are two employees in the Job

schema

The schema.js RootQuery should also be changed accordingly, in which case the query should be based on either Model find(if the parameter is empty, all data will be queried) or findById (by ID). The complete code looks like this:

const graphql = require('graphql')
const { 
    GraphQLObjectType,
    GraphQLString,
    GraphQLSchema,
    GraphQLID,
    GraphQLInt,
    GraphQLList
} = graphql
const _ = require('lodash')
const Person = require('.. /models/person')
const Job = require('.. /models/job')

// Create the Person structure
const PersonType = new GraphQLObjectType({
    name: 'Person'.fields: () = > ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        sex: {type: GraphQLString},
        age: {type: GraphQLInt},
        job: {
            type: JobType,
            resolve(parent, args) {
                return Job.findById(parent.jobId)
            }
        }
    })
})

const JobType = new GraphQLObjectType({
    name: 'Job'.fields: () = > ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        department: {type: GraphQLString},
        persons: {
            type: new GraphQLList(PersonType),
            resolve(parent, args) {
                return Person.find({
                    jobId: parent.id
                })
            }
        }
    })
})


const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType'.fields: {
        person: {
            type: PersonType,
            args: {
                id: {type: GraphQLID}
            },
            resolve(parent, args) {
                return Person.findById(args.id)
            }

        },
        job: {
            type: JobType,
            args: {
                id: {type: GraphQLID}
            },

            resolve(parent, args) {
                return Job.findById(args.id)
            }

        },
        persons: {
            type: new GraphQLList(PersonType),
            resolve(parent, args) {
                return Person.find({})
            }

        },

        jobs: {
            type: new GraphQLList(PersonType),
            resolve(parent, args) {
                return Job.find({})
            }
        }

    }

})

const Mutation = new GraphQLObjectType({
    name: 'Mutation'.fields: {
        addPerson: {
            type: PersonType,
            args: {
                name: {type: GraphQLString},
                sex: {type: GraphQLString},
                age: {type: GraphQLInt},
                jobId: {type: GraphQLID}
            },
            resolve(parent, args) {
                let person = new Person({
                    name: args.name,
                    sex: args.sex,
                    age: args.age,
                    jobId: args.jobId
                })
                return person.save()
            }
        },
        addJob: {
            type: JobType,
            args: {
                name: {type: GraphQLString},
                department: {type: GraphQLString}
            },
            resolve(parent, args) {
                let job = new Job({
                    name: args.name,
                    department: args.department
                })
                return job.save()
            }
        },
    }
})
module.exports = new GraphQLSchema({
    query: RootQuery,
    mutation: Mutation
})

Copy the code

conclusion

Today’s lesson will end here first. In the next lesson, I will introduce other relevant knowledge such as how to restrict users from passing in certain parameters to be successful during mutation