Hi guys! I think you are now familiar with the basics of Express framework. Last time I wrote an article to connect with MongoDB with Express. Now my goal is to fetch some data from a NO SQL MongoDB database. Let's see how to achieve the goal within the knowleadge we have.

First I need to tell you one thing. Since the need to shorten the article I have to use previosly  used concepts here.

Prerequisite :
NodeJS has to be installed on your machine

MongoDB has to be installed on your machine
Link : https://salitha94.blogspot.com/2018/06/introduction-to-mongo-db-and-installation.html

Start a NodeJS project by creating a simple web server
Link :https://salitha94.blogspot.com/2018/05/create-simple-web-server-with.html

If you have not aware of those things, read those blogs first! I will do from scratch here also but long explanations will be omitted sometimes.

Step 1 - Start a project in NodeJS

Create a project folder and and open it in VS code or any other text editor. Then initialize a project after navigating into project using cmd or terminal. My folder name is nodemongo.
npm init

Here give the entry point as app.js for the project. Otherwise it will take as index.js by default.
Then we have to install some node modules into our project after going into the project with cmd. For more details visit here.
npm install express --save
npm install nodemon --save
npm install mongoose --save

Create app.js directly in the project folder file now and include this code.

// Load express module
const express = require('express');

// Initialize app
const app = express();

// Mongoose connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/nodemongo');
const db = mongoose.connection;

// Check for DB connection
db.once('open', function(){
    console.log("Connected to MongoDB successfully!");
});
db.on('error', function(){
    console.log(err);
});

// Route for home
app.get('/', function (req, res) {
    res.send('hello world')
});

// Start server with port 3000
app.listen(3000, function(){
    console.log("Server started on localhost:3000");
});

Now the server is ready to run our project. Open a web browser and type  localhost:3000 to run the project. Output will be like this.

Step 2 - Create database and feed some data into it

Open MongoDB console by typing mongo on the terminal. Before that You must start MongoDB using mongod command. Then I create a new database called nodemongo. After that I need a MongoDB collection to store my records. In this example I'm going to use some blog records like in a Blog site. I will store some blog post records to the database first.
To create and select database : use nodemongo
To create a collection :  db.createCollection('posts')
To insert records :
db.posts.insert({title: "First Post", slug: "first-post", author: "salitha", description: "This is the post 1 description"})
db.posts.insert({title: "Second Post", slug: "second-post", author: "salitha", description: "This is the post 2 description"})
db.posts.insert({title: "Third Post", slug: "third-post", author: "salitha", description: "This is the post 3 description"})

Now the sample data has been added to the database collection. You can check them using this command.
db.posts.find().pretty()



Step 3 - Create a Router for the routes

Currently I have set routes within the app.js file itself. So there's a way to export these routes to another file and implement all the functions in that file. How to do it? In the project folder, create a new folder called routes. Then within this folder create a new file called posts. You can name it as you wish. But since I'm going to fetch some data relevant to a blog I name it as posts.

routes/posts.js

const express = require('express');
// Initialize app
const router = express.Router();
router.get('/', function (req, res) {
    res.send('home');
});
module.exports = router;

Step 4 - Modify the app.js to use router

We have exported the Router using a router variable in routes/posts.js file. Now we have to use this router in our app.js file. There's a simple mechanism to do this.
When you type localhost:3000 in the browser, it loads the response we sent and display home in the browser. But think if you want to change the URL to localhost:3000/posts and then view the home. So, there you want a simple configuration in app.js file. We need to define it like this..

const posts = require('./routes/posts');
app.use('/posts', posts);

We assigned the route file path to a constant. Then we need to tell to the application to use that kind of routes in a specific way. I have given a parameter like '/posts'. This is the URL segment comes after localhost:3000 for the routes included in posts.js file.

In the posts.js file, I have given the path for the function returning home as '/'. That means ADD NOTHING after posts URL segment. Always router will append the segments passed by the each function.
Usual Route format  =>  localhost:3000/posts/segment1/segment2
Since we add nothing here to the URL, the route for home now => localhost:3000/posts
If I replaced '/' with a word like '/list', then the route for home will be => localhost:300/posts/list

Step 5 - Create a Schema

Since we are using MongoDB, we need a Schema to connect the data to the posts.js file. Schema is simply a definition of the database we are using. Within the project folder, create a folder called models. In this folder, create a new file called post.js. In this file finally we export the model to the outside. Place this code in post.js.

models/post.js

const mongoose = require('mongoose');

let postSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    author: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    }
});

let Post = module.exports = mongoose.model('Post', postSchema);

Step 6 - import the model to posts.js file

routes/posts.js

Place the below code in posts.js file to load the model.

const Post = require('../models/Post');

Step 7 - Modify the route to load posts

Now we have to final task. Using the Schema we created, we can load the posts stored in database. Modify the route like this.

router.get('/', function (req, res) {
    let posts = Post.find({}, function(err, posts){
        if(err){
            console.log(err);
        }
        else {
            res.json(posts);
        }
    });
});

Now type localhost:300/posts in the web browser. You will get the JSON array of the posts stored in database.


I think you are also getting this result on your browser. So, try to insert some new records to database ad retrieve all the objects again. This is the starting point to build up an API using Express and MongoDB. So, I will bring you a full article on creating a REST API using these technologies soon!

Good Bye!



8 Comments