Connecting To MongoDB Using Mongoose: Node.js

In today’s video tutorial lets learn to connect to MongoDB server from our Node.js application using Mongoose module.

node-mongoose-mongoDB

Mongoose Module
Mongoose provides a straight-forward, schema-based solution to modeling your application data and includes built-in type casting, validation, query building, business logic hooks and more..

MongoDB
MongoDB is one of the leading NoSQL database. Know more about it at MongoDB – Getting Started Guide

Related Read: MongoDB Tutorial List

Listing Mongoose As A Dependency
package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "nodemon app.js"
  },
  "dependencies": {
"express": "*",
"nodemon": "*",
"mongoose": "*"
  }
}

list the mongoose module as a dependency for your Node.js application

Install the dependencies

1
npm install

This looks for all the dependencies listed in package.json file and installs it. Make sure that your system is connected to the internet.

Connecting to MongoDB
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var mongoose = require('mongoose');
 
app.use(express.bodyParser());
app.use(express.methodOverride());
 
mongoose.connect('mongodb://localhost/Company');
 
var mySchema = new mongoose.Schema({
_id    : String,
name: String,
age   : Number
});
 
var user = mongoose.model('emp', mySchema);

We have to first include mongoose module into our application. We also need the help of bodyParser() and methodOverride() middlewares in order to parse the form variables and override method to make PUT and DELETE methods work.

Next we connect to mongobd using connect method of mongoose module. Here we also specify the mongoDB database name to which our application will be connecting to. If the database is not already present, this will create one for us.

Next, we write a schema definition for our collection. Mongoose uses schema for validation of user entered data. By specifying the data type for our field we can make sure user entries are validated against the data types we have mentioned in our schema.

Some valid Schema Types, supported by Mongoose
String
Number
Date
Buffer
Boolean
Mixed
Objectid
Array

Mongoose Model
A model in mongoose is an object that gives us easy access to a named collection, allowing us to query the collection and use the schema to validate any document we save to that collection.

Connecting To MongoDB Using Mongoose: Node.js


[youtube https://www.youtube.com/watch?v=93APwwh35PA]

YouTube Link: https://www.youtube.com/watch?v=93APwwh35PA [Watch the Video In Full Screen.]



Note 1: In above example code, we are creating a collection called emp and binding it with the schema mySchema

In above example
Database name: Company
Collection/table name: emp

Note 2: Make sure MongoDB server is up and running, before you execute your Node.js application.

Checking If your application succesfully connected to MongoDB Server!
app.js

1
2
3
4
5
var db = mongoose.connection('mongodb://localhost/Company');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  // all your database operations(CRUD) here 
});

Here by using on method we check if we could successfully connect to our mongoDB server. If there was any error, we output the error on to the screen. If the connection is successful, we’ll continue with our CRUD operations on the database tables.

Connecting To MySQL server From PHP

Most application programs need to be connected to the database inorder to do some basic operations like saving and retrieving the user details / data.

In this video tutorial we illustrate, how we need to connect to MySQL server from PHP script.

Connecting to MySQL server
db.php

1
2
3
4
< ?php
$conn = mysql_connect('localhost','root','');
$db   = mysql_select_db('database_name', $conn);
?>

Include this file in all other files which needs to communicate with this database database_name

1
2
3
4
5
6
< ?php
include_once('db.php');
?>
 
INSERT, SELECT, UPDATE, DELETE, DROP etc ..operations 
on the datbase.

Video Tutorial: Connecting To MySQL server From PHP


[youtube https://www.youtube.com/watch?v=EAJ0XsQysf8]

YouTube Link: https://www.youtube.com/watch?v=EAJ0XsQysf8 [Watch the Video In Full Screen.]



There are many variations of include:
include();
include_once();

require();
require_once();

require produces fatal error if the required file is not found. include produces warning when the file is not found.
include_once and require_once makes sure the files are included only once and not included multiple times in the same file.