How to create a basic API in Express and NodeJS Part 3

Alex
6 min readJul 31, 2019

In my previous tutorial I wrote about creating a root api call as well as running the API on localhost, in this tutorial however, we will be learning how to create a MongoDB schema and then creating an instance of this schema to our database we made in previous tutorials.

Schema — A schema is used to define the properties of a document.

The first step is to create a folder in the root of your project named “schema”, within this folder create a file named whatever you like ( I have called mine “LetterEntrySchema”)

You will then need to include the mongoose package in this file as the Schema object is a part of this object and you can do this with the code:

var mongoose = require('mongoose');

Secondly, you will need to create a variable that is equal to Schema constructor so you can access the functions of “Schema” like so

var Schema = mongoose.Schema;

You can then begin to create your Schema like so

var LetterEntrySchema = new Schema({letterInRussian:{
type:String,
},
letterInEnglish:{
type:String
},
CreatedDate:{
type:Date,
default:Date.now
},
exampleSentence:{
type:String
},
soundFileName:{
type:String
}});

There are many Schema types available under Mongoose, too many to go over in this tutorial anyway! If you wish to learn more about these then go to this link

Basically a schema type is used to define the properties of the document as well as what kind of data each property should accept and since my schema is very basic it only uses String & Date, however, more complicated schemas will contain default values, validation, number, arrays and boolean values.

The next step is to export a “model” of the Schema so it can be used in our “server.js” so we are able to make instances of this Schema and send data to our database.

The code to do this is below

module.exports = mongoose.model('Letters',LetterEntrySchema);

As you can see I am using “module.exports” to tell JavaScript I want to export the model from the file, “mongoose.model” is a function used to create a model, with an instance of a model being a “document”, the models responsibility is to read and write these documents to and from the MongoDB database. The first parameter is the name of the collection that the documents will be inserted into, with the second parameter being the variable that contains the instance of the Schema constructor.

And that is it for a our Schema building lesson!

Now go back to your server.js file and import the model like so

var letterSchema = require('./schema/LetterEntrySchema');

Now import your file with code that will be similar below

var letterSchema = require('./schema/LetterEntrySchema');

You can change the variable name, also, just to take note your file name may be different to mine so if you copy and paste the above code you will need to change it to the name of the file you created your schema in.

If you remember in my previous tutorial I mentioned to comment out the line

mongoose.connect(mongoDB,{useNewUrlParser:true});

Now you can uncomment this as we will now be making requests to our database.

To make a request to our MongoDB database we first need to create another endpoint but this time it will a “POST” request meaning that we want to send data to the server in our “POST” request body.

app.post("/letters",function(req,res){var newLetter = new letterSchema({
letterInRussian:req.body.letterInRussian,
letterInEnglish:req.body.letterInEnglish,exampleSentence:req.body.exampleSentence,soundfileName:req.body.soundfileName});newLetter.save(function(err){if(err){console.log("Error when saving: " + err);}else{res.send({message:"Letter saved"});}});});

“app.post” represents an endpoint of express that uses the “POST” method, we will then need to enter a root path which is relative to the functionality of the request and for this example it is “/letters”, if your project was about books it would be suitable to call the endpoint “/books”, the second parameter is a callback function with 2 parameters “req” and “res”, representing the request and response object.

The next step is to create an instance of the model we imported from our schema this will then need to contain an object that has keys equal to the names of the properties defined in the schema, meanwhile, you will need to set the values of these properties equal to “req.body.nameOfBodyProperty”, the “req.body” means the body of the request, so when you send a request to an API from a program such as postman or from a react app with html elements such as a textbox you should make the name of the html element equal to the “req.body.putNameOfHtmlElementHere”. An example is if you have an input of type like the code below.

<input type="text" name="firstName" placeholder="my name is unimportant"/>

in your document you will need something like this where the value after “body.” is the same as the name of the input element.

var newLetter = new letterSchema({
firstName: req.body.firstName
});

After you have made an instance of this you will need to call the “save” method of Mongoose which will save the document to the database. In addition, it is good practice to include a callback function inside of the save function to allow for error handling and if you want to send a message to the user after their document has been inserted.

newLetter.save(function(err){if(err){console.log("Error when saving: " + err);}else{res.send({message:"Letter saved"});
}
});

So all in all our new “POST” method looks like the below.

app.post("/letters",function(req,res){var newLetter = new letterSchema({letterInRussian:req.body.letterInRussian,letterInEnglish:req.body.letterInEnglish,exampleSentence:req.body.exampleSentence,soundfileName:req.body.soundfileName});newLetter.save(function(err){if(err){console.log("Error when saving: " + err);}else{res.send({message:"Letter saved"});}});});

Now lets give this a whirl! Start up your project with “npm start”, also open your API development environment whether that be Postman or Insomnia.

As you can see I have created a “POST” method equal to “http://localhost:3000/letters”, so the Node JS program will look for a “POST” method with the endpoint “/letters”, in addition, I have included an object in the body of the request which has keys that are equal to the properties of the schema I made (excluding createdDate, but that has a default value so no need to worry about that!)

var LetterEntrySchema = new Schema({letterInRussian:{type:String,},letterInEnglish:{type:String},CreatedDate:{type:Date,default:Date.now},exampleSentence:{type:String},soundFileName:{type:String}});

After clicking the “send” button I can now see that I have received a successful response from the server.

Now lets check in our MongoDB database in MLab to see if the letter has been saved!

From the screenshot below you can see that the document has been saved to the collection successfully and our API can now save to a database, well done to you!

;)

This is the end of my mini series of creating a basic API in NodeJS and Express, there are a multitude of things you can do with NodeJS and it is worth exploring the Express documentation as it is very well written and worth reading.

Once again thanks so much for reading this article, I hope you learned something from this, I know I did! If you have any questions/feedback or criticisms feel free to leave a response on this article.

Have a good day!

--

--