...

/

Returning Data from a Database

Returning Data from a Database

Learn how to read data from a MongoDB database in GraphQL resolvers.

We’ve managed to get our database up and running and have even populated it with some seed data. Now, it’s time to integrate it with our application.

New file structure

In this lesson, the directory structure of our application will change slightly, and we will add a few more files and directories:

  • model: A directory that will contain all the Mongoose models we’ll use to interact with the data in our database.
  • mongo.js: A command that configures the connection to MongoDB.
  • logger.js: A logger’s configuration.

Here’s how we’ll organize our project:

Press + to interact
src
├── index.js
├── logger.js
├── models
│ ├── Category.js
│ └── Product.js
├── mongo.js
├── resolvers.js
├── schema.graphql
└── schema.js

Defining a Mongoose model

Now that we have a running database with the seed data, the only remaining thing to do is to read data from it in our application. To do this with Mongoose, we need to define a schema object for each MongoDB collection we plan to work with. We have three collections in our application, so we’ll have to define three schemas.

A schema in Mongoose defines a structure of objects that will be stored in a particular collection. To define a schema, we need to provide a list of fields, an object that a particular collection will contain, and their types. In this course, we’ll use the following types:

  • String
  • Number
  • Date
  • ObjectId (a type that represents IDs in MongoDB)
...