MongoDB Getting Started 01

Video Tutorial


MongoDB Is a document-oriented database program widely used for web projects and apps, it uses the NoSql (None Rational) Data Structure which makes it very perfect for web development since it uses the JSON Data Storage Structure, it is free and open source available for cross platforms also gonna allow you to easily manipulate data and submit queries using Schemas and Modals.

Getting Started 

First Install MongoDB on your machine it is freely available for multiplatform also make sure to remember your installation path since you are going to need it whenever you want to start the database server, the other thing we need is to install the Mongoose module which will allow us to interact with the database (it’s a wrapper on the main module) you can use the official MongoDB module but mongoose is more suitable for node.js apps.

So make sure to set up a nodejs project and install mongoose

npm install mongoose --save

MongoDB Schemas

MongoDB is based on the JSON Structure which means there are no tables or columns like MySql or SqlLite rather than that it uses collections (tables) to store the attributes (key-value pairs), so first on we need is to define our schema and compile it into a modal that we can use for initiating new objects and save them into our database.

Create a new File name it modal.js that will store the return our compiled schema

//Import Mongoose and Schema from Mongoose Module
const mongoose = require('mongoose');
let Schema = mongoose.Schema;

Now we create the Schema, think of it as a javascript object if you are already familiar with JSON this gonna be very easy for you to manipulate

//We create an User Schema that is going to be stored on our database 
let User = new Schema({
    username: {
        type: String, ///< Specify the Type of this Field 
        required: true ///<  Required Will force you to complete this filed 
    password: {
        type: String,
        required: true
    created_at: {
        type: Date, ///< You can Also Assign Custom Objects/Classes as a Data Type 
        default: ///< This will be the Default value, no need for insearting it 

And this how the schema is structured, you can as many fields/attributes as you wish either by specifying the custom attributes (type, required, default…) or no.

Now we need to compile our schema into a modal in order to use it for either saving an instance to the database or searching, updating and deleting already stored objects which we will cover in the next tutorials.

//We export the Compiled Modal using NODE.JS In order to import it in the main database handler 
exports.user = mongoose.model('User', User); ///< modal method will compile your schema giving it a // name

Our Schema is ready and compiled so now we need to connect to the database and save a sample data instance of our user object

So we need to run the MongoDB service (server), make sure to cd into the right local disk where you have installed the MongoDB binaries for ex: local disk C then run this command


Create a new file named dbTest.js where we are going to handle the database connection and interaction

//Import Mongoose and Our Compiled Module from modal.js 
const mongoose = require('mongoose');
User = require('./modal').user; ///< we access the exported module

//Connect to the Database
mongoose.connect("mongodb://localhost/users", err => {
    if (err) console.log("MongoDB Error: ", err);
    else console.log("Connected To Database");
/* we connect by providing a Remote url, but since we are running the server on our localmachine so we use localhost and the mongodb protocl to connect to the database. */
//Also We specify the database name users

The database will be created with the specified name if not already otherwise it will link you to it and call the handler when the operation is completed with an error object if there is any.

Let’s create a user with a username and a password and try to save it into the database

//We create the user using the specified data
let robot = new User({ username: 'Robot', password: '1234' });
//We save it on the database, user) => {
    if (err) console.log('Cannot Save');
    else console.log(user);

The save method on the modal passes in the newly created user as the second parameter to the callback so you can use it to check if all of your data are right.

Run the app using node

node dbTest.js 
Connected To Database
{ created_at: 2018-02-10T12:31:07.302Z,
  _id: 5a7ee60b5aa3e922141b2955,
  username: 'Robot',
  password: '1234',
  __v: 0 }

as you can see our app is working fine and if have noticed that MongoDB has created a unique ID specifically for us and this is being done automatically and you can control it for you specific options check DOCS for more info.

MongoDB Is being shipped with a program (MongoDB Compass) that provides you with a GUI Interface that allows you to manage your databases, so you can use it to check for the saved user data and debug your applications.

No Comments Yet