Episode 5: Create MongoDB Schema & Relationships (evernote clone)

Photo by Tianyi Ma on Unsplash

In the previous episode, we installed and set up mongoDB. If you missed it you can check it out here → Part 4

In this episode, we will be creating our mongoDB Notes and Users schema and making references between the two.

Agenda:

  • Install Mongoose
  • Create Notes and Users schema (with reference between)
  • Add create user mutation

Install Mongoose

STEP 1: Open up the project folder cd evernoteclone or drag and drop folder into editor.

STEP 2: run yarn add mongoose or for NPM lovers npm install mongoose to install the mongoose package

you’re all set with mongoose :)

Create Notes and Users schema

STEP 1: Inside the main directory (evernoteclone folder) create a model folder, inside create a users.js and notes.js files

STEP 2: Inside the notes.js file this is what we will add

  • Packages to include in this file
const mongoose = require('mongoose)
const schema = mongoose.Schema

This brings in the mongoose package of course, along with storing the schema in a schema for easy use when creating the models.

  • After adding those, we can create our notes model and all the necessary fields we need (which are the same ones we specified in our build schema).
// required packages are here...const notes = new schema({
title: {
type: String,
required: true
},
content: {
type: String,
required: true
},
image: {
type: String
}
userCreator: {
type: schema.Types.ObjectId,
ref: "User"
}
})
module.exports = mongoose.model("Notes", notes)

Here we are creating our schema for our notes model we want in our DB and what fields it should have. Now, the userCreator might look a little funny. The type of field is an ObjectID and this is basically saying we want this userCreator field to store an ObjectID of the user that created this note. In order to make this reference we use the ref to tell mongoDB that the ObjectID should be connected to whatever the user’s ObjectID is going to be. We haven’t created the user model yet, but when we do, we’ll make that connection as well.

The last thing to do was export this schema so we can use it in other files. To be specific we exported the model, the 1st param is to specify the name of the model "Notes” . The 2nd param says what schema are you using for this model notes .

Side note: If you noticed I didn’t add the required property to images, mostly because adding images will be optional on the frontend. The rest of the other fields are required.

STEP 3: Go into the users.js file now.

  • Lets do the same in our users.js file, copy the same packages as in our notes.js file
const mongoose = require('mongoose)
const schema = mongoose.Schema
  • After that, let’s create our users model now.
// required packages are here...const users = new schema({
username: {
type: String,
required: true
},
email: {
type:String,
required: true
},
password: {
type: String,
required: true
},
createdNotes: [{
type: schema.Types.ObjectId,
ref: 'Notes'
}]
})
module.exports = mongoose.model("Users", users)

Here we are creating our schema for our user model we want in our DB and what fields it should have. In this schema we have the createdNotes which is just an array of ObjectID’s of the notes this user created (basically the note id’s goes here). Again, we made this connection using the ref property to let mongoDB know the array of ObjectID’s comes from our notes model. Overall, every time a user creates a note it gets add to their createdNotes array. At the end we do that same as our notes model, export this model and named it "Users” and the schema it uses is the users schema

Create User Mutation

STEP 1: Head over to our schema.js file, this is where we need to add a mutation.

STEP 2: Inside our mutation object we should have currently have the following

// schema.js filetype Mutation {
createNote(noteInput: noteinput): Note!
deleteNote(_id: ID): Note
}

We should add the following:

type Mutation {
createUser(userInput: userinput): User!
createNote(noteInput: noteinput): Note!
deleteNote(_id: ID): Note
}

This mutation does the same as the notes mutation, only difference is that it’s creating a user with the values we specify. Then, it should return that user back to us (hint: User!).

STEP 3: With this mutation being added we need to adjust our types. Our build schema should now look like this

const ourSchema = buildSchema(`
type Query {
notes: [Note]
note(_id: ID): Note
}
type Note{ --> this is the object createdNotes is referring to
_id: ID
title: String
content: String
image: String
userCreator: User! --> added userCreator just like our model
}
type User{ --> this is the object userCreator is referring to
_id: ID
username: String
email: String
password: String
createdNotes: [Note] --> array of notes this user created
}

input noteinput{
title: String
content: String
image: String
}
input userinput{ --> fields needed to create user(same as model)
username: String
email: String
password: String
}

type Mutation {
createUser(userInput: userinput): User!
createNote(noteInput: noteinput): Note!
deleteNote(_id: ID): Note
}
`);
module.exports = {
ourSchema
};

As of now, this will be our current state of our schema. Any other dummy data that was there previously there, DELETE it lol.

That is it for this episode, I hope you guys enjoy :) and again if you would like to watch the video you can find it here → Create schema video

--

--

--

A passionate web developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Everything you need to know about the destructuring assignment in JavaScript

A Simple Guide to Understanding Javascript (ES6) Generators

The practical JS 12 factor application | I. Codebase

http://sensiblestart.blogspot.com/2021/02/are-my-dreams-too-big.html.

The Rise of JAMstack 🚀

Pick an Air Mattress That You WillLove https://t.co/UXX0kw1sdC

Build an Image Upload Application With React, NodeJS, PostgreSQL, and S3

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store

Ajea Smith

A passionate web developer

More from Medium

Dev IRL : How to add React components to an Express powered website using Create React App…

Developing Chrome Extensions With AWS Amplify Authentication

Handle API lifecycle with React, Axios and Redux Toolkit

Code to setup the APIStatus, APIError and APIData types

Testing with Node.js: Understand and Choose the Right Tools