CoffeeScript - MongoDB


Advertisements

MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document. For more information read our MongoDB Tutorial.

In this chapter you will learn how to communicate with MongoDB database using CoffeeScript.

Installation

The MongoDB database can be integrated with CoffeeScript using Node.js 2.0 driver of MongoDB. First of all you need to install MongoDB in your system, by referring the environment chapter of our MongoDB tutorial.

After installing MongoDB successfully browse through its bin folder (if you haven't set the path) and start the MongoDB service as shown below.

C:\Program Files\MongoDB\Server\3.2\bin> mongod

Finally install MongoDB driver and it's dependencies by executing the following NPM command in the command prompt.

npm install mongodb --save

Connecting to MongoDB

In order to connect to MongoDB, first of all create MongoClient using this, invoke the connect() function. This function accepts url, and a callback function as parameters.

Following CoffeeScript code shows how to connect to MongoDB server. If the MongoDB server is running in your system this program establishes a connection to the server.

#Requiring the Mongodb package
mongo = require 'mongodb'

#Creating a MongoClient object
MongoClient = mongo.MongoClient

#Preparing the URL
url = 'mongodb://localhost:27017/testdb'

#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url
    #Close connection
    db.close()
  return

Save the above code in a file with name connect_db.coffee and execute it as shown below. If database is successfully created then it will give following message

c:\> coffee connect_db.coffee
coffee connect_db.collection
Connection established to mongodb://localhost:27017/testdb

Creating a Collection

A collection in MongoDB holds the documents we store in it. You can create a collection by using the collection() function. This function accepts a string argument that represents the name of the collection we want to create.

Following CoffeeScript code shows how to create a collection in MongoDB. In case of any errors, they will be displayed on the console.

#Requiring the Mongodb package
mongo = require 'mongodb'

#Creating a MongoClient object
MongoClient = mongo.MongoClient

#Preparing the URL
url = 'mongodb://localhost:27017/testdb'

#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url
	
    #Create collection
    col = db.collection('My_collection')
    console.log "Collection created successfully."
	
    #Close connection
    db.close()
  return

Save the above code in a file with name create_collection.coffee and execute it as shown below. If the collection is created successfully then it will give following message

c:/> coffee create_collection.coffee
Connection established to mongodb://localhost:27017/testdb
Collection created successfully.

Inserting Documents

You can inset documents in to a collection in MongoDB you need to invoke a function named insert() by passing the list of documents that are needed to be inserted, as parameters.

Following CoffeeScript code shows how to insert documents in to a collection named My_collection. In case of any errors, they will be displayed on the console.

#Sample JSON Documents
doc1 = {name: 'Ram', age: 26, city: 'Hyderabad'}
doc2 = {name: 'Rahim', age: 27, city: 'Banglore'}
doc3 = {name: 'Robert', age: 28, city: 'Mumbai'}

#Requiring the Mongodb package
mongo = require 'mongodb'

#Creating a MongoClient object
MongoClient = mongo.MongoClient

#Preparing the URL
url = 'mongodb://localhost:27017/testdb'

#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url  
  #Creating collection
  col = db.collection('My_collection')
	
  #Inserting documents
  col.insert [doc1,doc2,doc3], (err, result) ->
    if err
      console.log err
    else
      console.log "Documents inserted successfully"
    #Close connection
    db.close()
    return
  return

Save the above code in a file with name insert_documents.coffee and execute it as shown below. If the documents are inserted successfully then it gives following message

c:/> coffee insert_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Documents inserted successfully

Reading Documents

You can retrieve the documents that are stored in MongoDB using a function named find(). The following CoffeeScript code shows how to retrieve the records that are stored in MongoDB.

#Requiring the Mongodb package
mongo = require 'mongodb'

#Creating a MongoClient object
MongoClient = mongo.MongoClient

#Preparing the URL
url = 'mongodb://localhost:27017/testdb'

#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection object
    col = db.collection('My_collection')    
    #Inserting Documents
    col.find({name: 'Ram'}).toArray (err, result)->
      if err
        console.log err
      else 
      console.log 'Found:', result			
      #Closing connection
      db.close()
      return
  return

Save the above code in a file with name read_documents.coffee and execute it as shown below. This programs retrieves the required document in the specified collection and displays it as shown below.

C:\> coffee read_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ { _id: 56e269c10478809c3009ad1e,
    name: 'Ram',
    age: 26,
    city: 'Hyderabad' } ]

You can also read all the documents existing in a particular collection by executing the find() function with out passing any arguments to it as shown below.

#Requiring the Mongodb package
mongo = require 'mongodb'

#Creating a MongoClient object
MongoClient = mongo.MongoClient

#Preparing the URL
url = 'mongodb://localhost:27017/testdb'

#Connecting to the server
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection object
    col = db.collection('My_collection')    
    #Reading all Documents
    col.find().toArray (err, result)->
      if err
        console.log err
      else 
      console.log 'Found:', result			
      #Closing connection
      db.close()
      return
  return

Save the above code in a file with name read_all_documents.coffee and execute it as shown below. this programs retrieves all the documents in the specified collection and displays it as shown below.

C:\> coffee read_all_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ { _id: 56e2c5e27e0bad741a68c03e,
    name: 'Ram',
    age: 26,
    city: 'Hyderabad' },
  { _id: 56e2c5e27e0bad741a68c03f,
    name: 'Rahim',
    age: 27,
    city: 'Banglore' },
  { _id: 56e2c5e27e0bad741a68c040,
    name: 'Robert',
    age: 28,
    city: 'Mumbai' } ]

Updating Documents

You can update the documents that are stored in MongoDB using a function named update(). Following CoffeeScript code shows how to update the records that are stored in MongoDB.

#Get mongo client object
MongoClient = require('mongodb').MongoClient
#Connecting to mongodb
url = 'mongodb://localhost:27017/testdb'
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection
    col = db.collection('My_collection')
    #Reading Data
    col.update {name:'Ram'},{$set:{city:'Delhi'}},(err, result)->
      if err
        console.log err
      else 
      console.log "Document updated"    
      
      #Closing connection
      db.close()
	  return
  return

This program updates the city of the employee named Ram from Hyderabad to Delhi.

Save the above code in a file with name update_documents.coffee and execute it as shown below. this programs retrieves the documents in the specified collection and displays it as shown below.

C:\> coffee update_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Document updated

After updating, if you execute the read_documents.coffee program, then you will observe that the city name of the person named Ram is updated from Hyderabad to Delhi.

C:\> coffee Read_all_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ { _id: 56e2c5e27e0bad741a68c03e,
    name: 'Ram',
    age: 26,
    city: 'Delhi' },
  { _id: 56e2c5e27e0bad741a68c03f,
    name: 'Rahim',
    age: 27,
    city: 'Banglore' },
  { _id: 56e2c5e27e0bad741a68c040,
    name: 'Robert',
    age: 28,
    city: 'Mumbai' } ]

Deleting Documents

You can delete all the documents from the collection using the remove() function. Following CoffeeScript code shows how to delete all the records that are stored in MongoDB.

#Get mongo client object
MongoClient = require('mongodb').MongoClient
#Connecting to mongodb
url = 'mongodb://localhost:27017/testdb'
MongoClient.connect url, (err, db) ->
  if err
    console.log 'Unable to connect . Error:', err
  else
    console.log 'Connection established to', url	
	#Creating collection
    col = db.collection('My_collection')
    #Deleting Data
    col.remove()
    console.log "Document deleted"
      
    #Closing connection
    db.close()	  
  return

Save the above code in a file with name delete_documents.coffee and execute it as shown below. this programs removes all the documents in the specified collection displaying the following messages.

C:\> coffee delete_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Document deleted

After deleting, if you execute the read_documents.coffee program, then you will get an empty collection as shown below.

C:\> coffee Read_all_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Found: [ ]
Advertisements