Getting started with Mongoose !!

07 / Apr / 2014 by ajay.mishra 6 comments

Mongoose is a Node.js package that gives you an interface to play with mongo database. Mongoose has all sets of methods that help you to connect and access data stored in database.
It translates data from database in javaScript object which you can provide to your application.

We will move step by step to know how it works.

1. Requiring Mongoose


1.1 First install mongoose in your project using--> npm install mongoose 

1.2 var mongoose= require('mongoose'); 

2.Connecting To MongoDB

mongoose.connect('mongodb://localhost/mydb'); 

mongoose.connect is useful for making only a single db connection.
You can get connection Instance by – var db=mongoose.connect;
db object is used to listen the events attached to it.

  • db.on(‘connected’, function () {//do the schema and query processing});
  • db.on(‘err’, function () {//display error message});
  • db.on(‘disconnected’, function () {//display db closed message});

3.Creating Schema


var userSchema = new mongoose.Schema({ name: String, email: { type: String, unique: true }, createdOn:{ type: Date, 'default': Date.now } }); 
//the above fields have been described in three ways 

schema is a way to describe structure of data in a database.

    Schema accepts only the following types.

  • String
  • Number
  • Date
  • Boolean
  • Buffer
  • ObjectId
  • Mixed
  • Array

4.Creating model


var User=mongoose.model( 'User', userSchema ); 
//User --> the name of model 
//userSchema -->> the schema to be compiled 

model is -::

  • A compiled version of the schema.
  • maps directly to a single document in the database

5.Creating and Saving Instances


var userObj1 = new User({ name: 'Ajay' });
var userObj2 = new User({ name: 'Raja',email:'mymail@gmail.com' }); 

these models can be saved in the database by ::-

  • userObj1.save(function(err){console.log(err);})
  • userObj2.save(function(err){console.log(err);})

6. Reading from DB
We have two approaches to find or read data

  • Using the QueryBuilder interface

var myQuery = User.find({'name' : 'Ajay'}); myQuery.where('age').gt(18);
myQuery.sort('age'); 
myQuery.select('name email'); 
myQuery.exec(function (err, userObjects){console.log(userObjects)});
 
  • With a single command

 Model.find(conditions, [fields desired], [options], [callback]) 
 // fields and options can be omitted 
 User.find( {'name' : 'Ajay'},function (err,userObjects){ if (!err){console.log(userObjects);} }); 

7.Updating the DB
using findById


User.findById(id, function (err,UserObj) { if (!err) { UserObj.name = 'Amit'; UserObj.save(function(err)
{ if (!err)console.log("saved successfully!!");}); } }); 

the other way to do it-

 
User.update({ _id: id }, { $set: {name: 'Amit' }}, callback); 

8.Deleting from DB
using remove()


User.remove({ name :'Ajay' },callback); 

So,these were certain set of steps which can be followed to use “mongoose” in your Node.js application.
Hope it helps!!

FOUND THIS USEFUL? SHARE IT

comments (6)

  1. liveprofits.co

    359341 14Hiya! Wonderful weblog! I happen to be a everyday visitor to your web site (somewhat a lot more like addict ) of this site. Just wanted to say I appreciate your blogs and am searching forward for a lot more! 410987

    Reply
  2. kakkoo.com.au

    You could certainly see your enthusiasm in the
    article you write. The sector hopes for even more passionate writers such as you
    who are not afraid to say how they believe. All the time go after your heart.

    Reply

Leave a comment -