Как пользоваться системой
Огородники01 июля 2020

Как пользоваться системой

Responses (3)


What are your thoughts?

Alejandro Vivas

22 days ago

Hi, first of all. I really appreciate your work. Thank you for your tutorial. Also, I wanted to know how the buildSchema.js works. I mean, I don’t see where is it call when I start muy build script. Can you explain a little how it works? Thanks in ad...

Read Moredfasdf

Mark Rabey

7 months ago

Great post, very helpful. Had to look up the health check endpoint, but that’s fine. When does the buildSchema script get called? You mention adding it the the yarn build script, but you don’t seem to go back and do that. Running it on it’s own I get some errors because the data folder doesn’t exist.

Jan Schoppenhorst

8 months ago

At least one example how to use the playground would be nice. I have to get this information elsewhere, which feels like an anti-climax when reaching the end of the article. Besides that, good article.

You have 1 free member-only story left this month. Upgrade for unlimited access.

Create a GraphQL API With Node.js, Mongoose, and Express

Get started with GraphQL, and build your first API.

GraphQL is a technology that helps developers build robust software more quickly. The ability to request all of the information you need in a single request is a game changer.

It has simplified the back-end development of APIs for consumption by mobile and web applications that would normally rely on RESTful APIs. A normal RESTful API may have several end points for various entities (e.g., users, submissions, etc.); with GraphQL, you can get all of this information in a single go using GraphQL’s query language, also known as GQL.

In this tutorial, I’ll walk you through how to build a GraphQL API with graphql-compose-mongoose, as well as a few other tools. And, of course, everything will be to ES6 spec using Node.js. If this sounds like an exciting adventure, read on.

Getting Started

To get started, we’ll need to double-check you have a few prerequisites to ensure both that you understand the technology and that you can complete the tutorial in full.


  • Node.js (Latest 13.x or above)
  • Yarn (brew install yarn on macOS)
  • An understanding of JavaScript and the ES6 spec
  • An account with MongoDB Atlas or a local instance of MongoDB running

Directory Structure

To start, create a new directory.

You can name your directory whatever you would like; for this tutorial, we’re going to create a to-do application, so I called mine todo.

Next, let’s go ahead and generate our package.json file using Yarn. We’ll add modules, as necessary, as we continue to move forward.

Note: Answer the questions as prompted. Nothing necessarily required here — just whatever you’d like to set as your defaults.

Because we are using ES6, we’ll need to transpile all code from ES6 to vanilla JavaScript. To do so, let’s go ahead and create a src directory. Note that we’ll also need to set up the required structure within the src. The script below will accomplish the following:

  • Make a src directory
  • Move into the src directory
  • Generate schema, models, scripts, and utils directories

Lastly, we’ll create an index.js file, which will allow us to import our dependent files and directories:

Inside of index.js, place the following contents, and save:

Package File

Now that we have the base files in place, let’s go ahead and add the required production packages to our package.json file using Yarn, like so:

And for development packages, add the following:

Now that we have the necessary packages installed, we can modify our package.json file to allow for additional functionality.

Let’s modify it to add scripts and hooks; once we’ve done that, your package.json file should look much like this:


The below will allow us to run scripts via Yarn (e.g., yarn <INSERT SCRIPT HERE>). For example, we can lint our code using yarn lint, and it’ll perform ESLint and Prettier operations on our files.

Similar to above, we’ll add a Husky script that will trigger on the precommit event, effectively running yarn lint for us prior to committing code.

This is an excellent practice for maintaining quality, clean code:

That’s all for scripts. Let’s continue on.

Configuring Babel, Prettier, and ESLint

We’ve taken the necessary steps to install the correct packages for Babel, Prettier, and ESLint.

Now, it’s time to add the configuration files to the root of your project. Move the root, and add the following files:




Perfect! We’re making progress.

Onto the next section.

Creating Our Models

The reason I enjoy working with graphql-compose-mongoose is that it allows me to use Mongoose models rather than writing GraphQL models by hand (which, by the way, can become quite cumbersome on a large application).

Head over to src/models, and create a new file named user.js. Inside this file, we’ll define all of the required characteristics that make up a user. This will be a small file, but feel free to add additional information to the user record if you wish (for example, a password using mongoose-bcrypt).

Next, let’s create a task.js file (given that this is, after all, a to-do GraphQL API):

We now have two models/schemas: UserSchema and TaskSchema.

A user is an individual entity, and a task always belongs to a user. From this, we will eventually be able to pull all tasks for a user in a single GraphQL call. Pretty cool, right?

Creating Our Schemas

Schemas are an interesting part of this implementation. They, essentially, allow us to define what calls can and cannot be made to the server.

Schemas are made up of queries and mutations, where queries allow you to fetch data, and mutations allow you to modify data. Let’s create our schemas for both the user and task model.

Inside of the schema directory, create a file called user.js. Then, drop the following contents into the file:

Next, let’s create one called task.js:

To tie things together, we’ll generate an index.js file in the root of the directory (src/schema) and import our schemas:

Now that we have full CRUD capabilities with GraphQL, let’s add our final utilities.

Build Script

The build script allows you to transform your Mongoose-style schemas into pure GraphQL schemas. Pretty fancy, huh?

Create a file called buildSchema.js inside of src/scripts, and drop the following code in:

This file will be called with the yarn build command and will output the raw GraphQL queries into a data directory.

Database Connectivity

What’s an API without a database? That’s why we’ll need to create a connection from Mongoose to MongoDB.

If you haven’t already created a .env file in the root directory, now’s the time to do so. You’ll want to ensure it has the following environment variables:

Once your .env file’s in place, let’s go ahead and create another file inside of src/utils. Name the file db.js, and add the following contents:

Note: If you don’t have MongoDB up and running locally, MongoDB Atlas is a great alternative. Not only is it free, but it packs enough power on the free tier to run a development application without any issues. Check it out here.

The Playground

Your GraphQL is now complete. Run the command yarn dev, and you’ll be able to spin up the playground for GraphQL, which allows you to add, modify, remove, and query users and tasks — all in one call.

It looks a little something like this:


This quick-and-dirty tutorial is just the beginning of all the fun you can have using GraphQL to make your development stronger, cleaner, and more efficient.

Try expanding on what you’ve just built to add additional functionality to the models, or venture out on your own to improve one of your existing applications — or even spin up a new one; I’d love to hear more about all that you decide to do.

Until then, thank you for following me along throughout this tutorial, and stay tuned for future updates. Happy coding!

Better Programming

Advice for programmers.




853 claps

3 responses


Nick Parsons


Technical Writer🖋 Coder 👨‍💻 Outdoor Enthusiast 🏔️ Wannabe Astronaut 👨‍🚀 https://nickparsons.io 🔗

Better Programming


Advice for programmers.

See responses

Discover Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Make Medium yours

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Become a member

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade




Написать комментарий
💬 Последние комментарии
Весёлый Роджер
Ось вот оно ЩИРОЕ СЧАСТЬЕ – всё же е!!! Ну так скакуны - цэ ж почти ПЕРЕМОГА З ПОКРАЩЕННЯМИ! Ось яка же цэ добра новина! «В Украине снизился уровень благосостояния на 9% в долларовом выражении» И …. Г Л А В Н О Е …. «Более существенно обеднели жители России - на 10,7%, …» Ну прямо щирый бальзам на свидомую душу! Остальное можно не читать – с ранку – Всесвидомый Праздник! Танцують уси! Хай живе Гетмань Зе з роялью тай него жинка Олена! Сала пропиндосному режиму! Сала рагульему роду – що ни мае переводу!
Весёлый Роджер
«Елена 08 августа 2019 ….,я же тысячу раз говорила, Америка с нами и Запад тоже,а значит что?Это значит что деньги дадут,им это недорого, ещё напечатают,на фоне своих печатаний денег,Украине по сравнению с ними,копейки достаются, спокойствие граждане, только спокойствие.» Быть проституткой чи пыдарасом в колонии США – это почётно и выгодно!
Проституция - это настолько серьезно и доходно,что помимо комитета в Верховной Раде заслуживает и отдельного министерства в кабмине. Странно,что ее не вынесли на опрос наряду с канабисом во время завтрашнего голосования.
Весёлый Роджер
Вот как раз я процитировал пример, когда Шмуля спорил с Другой Еленой про финансы, и как всегда проигрывал, и как всегда попытался тупой матерщиной выиграть спор! Ну и где же была эта баба Вера? Да ни где, это сам Шмуля и есть. Или она шизофреник тупая. Ты ВСЁ правильно Луночка написала, а помнишь как он тролил других ребят, причём ни за что, за иное мнение. Так что поддонок он и мразь ждб продажная.
Весёлый Роджер
«Елена – 12 октября 2020 - Уёбок дебильный,какие там 25 трлн.?там реально многократно выше долги идут,если ты пидарасина хуесосная и жопадающая вафлеглотина не знаешь ничего,сиди в своём свинарнике и не отсвечивай,гнида.» "...люди они такие,со своими слабостями, поэтому имеют право на ошибку" "Спасибо, что без своей "изюминки" в конце..." - то бишь без Сало уронили - убийцам мало!
Весёлый Роджер
Ой да на кого ж ты нас покидаешь баба Вера? Да як жешь Шмуля пердун будэ без тебя житти, ему ж надо тапереча про нового клона думовати. У этого точки и большие буквы, а у нового наверно будут вместо точек тире ...---. Ну щоб тупые лохи читачи тут не додумовались, шо цэ не он - простой ждб пропахандон! "ПАКЕДА бабанька", не кашляй ...хорошо было с тобой...со СТАРОЙ КЛЮКОЙ... да не ой! Примитивно правда было, ну и понятно, прапорщики с каптёрки, мозгами никогда не блистали, ну да, пристыдить другого в том, он цитирует матерщинника, с которым пани хотела в разведку. И баба Вера, она же фанера, но у Роджера НИКОГДА не закончатся матерные фразы мудака Шмули, их там на два тома хватит.
Луна-2 - думаю что меня подде
К ого ты материшь- да, каждого -кто тебя критикует - за эти годы я достаточно насмотрелась на твои" веселые" выходки...