Search⌘ K
AI Features

Returning Data from a Database

Explore how to integrate MongoDB with a GraphQL backend by defining Mongoose schemas and models. Understand how to read and return data asynchronously using resolvers, and handle nested data queries efficiently within a full-stack application.

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:

Javascript (babel-node)
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)

Now, let’s define a schema for the products collection.

Javascript (babel-node)
// server/src/models/Product.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
name: String,
description: String,
url: String,
numberOfVotes: Number,
publishedAt: Date,
authorId: Schema.Types.ObjectId,
categoriesIds: [Schema.Types.ObjectId]
})
module.exports = mongoose.model('Product', ProductSchema)

As you can see, the schema ...