Mongo with mongoose

Work with MangoDB using mongoose in Nodejs-Express app


MangoDB is a NoSQL database which can be backend for web/mobile application. Working with Nodejs Express app, what I feel is Python Flask like environment, rendering, templating etc everything in place.

Mongoose

Mongoose is MangoDB modeling tool, which is designed to work with asynchronous environment (none blocking code). The following is required to use mongoose in your app

  1. mongoose module
  2. Connection string
  3. Schema
  4. Model

Install Mongoose

Install mongoose  from npm library by executing command on the terminal

npm install mangoose -save  *

*The save option will add mongoose into dependecies section of package.json (do you know, can install all dependencies of  project by firing npm install command on shell)

Setup mongoose

Let’s use the module , by setting up the connection url, schema and model. First up all add the require section to use mongoose as follows

 var mongoose = require('mongoose');

Connection

Now we are ready to setup the connection. Create database, add users and document at Mongoose.com and grab your connection string and the string will look like following. Also  enable firewall settings

mongoose.connect('mongodb+srv://<users>:<password>@cluster0.cqnll.mongodb.net/<databse>?retryWrites=true&w=majority');

replace  string <database> with database name , <user> with user name and <password> with password.

Schema

We have to structure the document with fields required , we can call it schema. Define one as you wanted. My schema use on one field

 //Schema

 todoSchema = new mongoose.Schema({ item: String });

Model

A model is the link between MongoDB Documents and the Nodejs. Through the Model we can interact with MongoDB documents. Here is our model

var Todo = mongoose.model('Todo', todoSchema);

Getting documents

so lets’ get some data. How do fetch documents

(Every row in SQL database is representing a line of data, in NoSQL DB it is referred as document) .

You can search for specific data or fetch all of them using Find method, which is provided by the mongoose.

         Todo.find({}, function(err, data) {

             if (err) throw err;

             res.render('index', { todos: data });

         });
or you can find specific document using
         Todo.find({item:'Buy some flower'}, function(err, data) {

             if (err) throw err;

             consloe.log(data.item);

         });

Save new document

Saving new document by creating a new model instance  as follows

 var newTodo = Todo({ item: req.body.todo_content }).save(function(err, data) {

             if (err) throw err;

             console.log('Item saved');

             res.redirect('/');

         });

Deleting document

Various method can be used for find and then delete a document. The simplest and purest one is using document id of document, it can’t be wrong since the document id is generated by Mongo itself.

 Todo.findByIdAndDelete(req.params.id, function(err) {

             if (err) console.log(err);

             console.log("Successful deletion");

             res.redirect('/');

         });
The above code is from a sample project, you can explore it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.