Node js connect to MongoDB using mongoose

Node js connect to MongoDB using mongoose

Almost every application web-based or otherwise requires data storage of some kind. And the applications you build with node are no different

In the early days of the database World, non-relational databases were the norm but relational databases slowly gained in popularity and over time became the mainstream choice for applications both on and off the web. In recent years, a resurgent interest in non-relational DBMS has emerged as they are proponents, claiming advantages in scalability and simplicity, and these DBMS Target a variety of usage scenarios. They are popularly referred to NoSql, interpreted as no sequel or not only SQL.

Although relational databases sacrifice performance for reliability many NoSQL databases put performance. First for this reason. No SQL databases. Maybe a better choice for real-time analytics or messaging NoSQL databases also usually don’t require data schema. To be predefined which is useful for applications in which stored data is hierarchical. But whose hierarchy varies in this section. We will look at two popular NoSQL databases radius and MongoDB. We will also look at Mongoose. A popular API that abstracts access to MongoDB adding a number of time-saving features.


Mongodb is a general-purpose non-relational database. It’s used for the same sorts of applications that don’t use rdbms for.

A MongoDB database stores documents in collections. Documents in a collection. As shown in the figure need not share the same data. Each document could conceivably have a different schema. This makes MongoDB more flexible than conventional RDBMS. As you don’t have to worry about redefining, schemas the most mature, actively maintained MongoDB API. The module is Christian armor. Not MongoDB, native. You can install this module using the following npm command Windows users. Note that the installation requires MSBuild.exe, which is installed by my secret soft Visual Studio.

npm install mongodb

Connecting to MongoDB

After installing the mongodb server, use the following code to connect to a MongoDB.

var mongodb = require('mongodb');
var server = new mongodb.Server('', 27017 , {} );

var client = new mongodb.Db( 'nodejstips', server, {w: 1}); 

Accessing the MongoDB collection

The following snippet shows how you can access a collection owns. The database connection is open if at any time. After completing your database operations, you want to close your MongoDB connection, execute client.close().{

  if(err) throw err ; 
  client.collection('atiq_users', function (err, collection){

     if(err) throw err; 
     console.log('we are connected to collection'); 

How to Insert Data into MongoDB

The following code inserts a document into a collection and prints. It unique document ID.

   "title": "Aws atiq", 
   "body": "I am an AWS Expert"
 {safe: true },
 function (err , documents){
  if(err) throw err; 
  console.log('Doc ID is '+ documents[0]._id);

Update Data Using Document ID

BSON (binary JSON) document identifiers can be used to update data. The following code shows how to update a document using it’s ID

var _id = new client.bson_serializer.objectID('484893485hg9348sw984huie9849r'); 
    {_id: _id},
    {$set: {"title": "This is good"}},
    {safe: true },
    function (err){
        if(err) throw err ; 

Searching for documents

To search for documents in MongoDB, use the find method. The following example shows logic that will display all items in a collection with title “AWS”

Collection.find({"title": "AWS"}).toArray(
    function (err, result ){
        if (err) throw err ; 
        console.log( result );

Deleting Documents

What to delete a row? you can delete a record by referencing it’s internal ID using code similar to the following

var _id = new clientInformation.bson_serializer.objectID('484893485hg9348sw984huie9849r'); 
Collection.remove({_id:_id}, {safe: true},
        if(err) throw err; 

Mongodb is a powerful database and node mongodb, native offers high performance access to it. But you may want to use an API that abstracts database access and Link the details for you in the background. These allows you to develop faster while maintaining few lines of code. The most popular of these API is called mongoose.


Learnboots’s Mongoose is a node module that makes using MongoDB painless. Mongoose’s models provide an interface to MongoDB collections and additional useful functionality such as schema hierarchies, middleware, and validation. Is Kima, hierarchy allows the association of one model with another enabling, for example, a blog post to contain Associated comments. Middleware allows the transformation of data or the triggering of logic during model data operation making possible taxes like automatic pruning of child data when a parent is removed. Mongoose validation support, lets you determine what data is acceptable at the schema level rather than having to manually deal with it. Although we are focused solely based on basic users, of mongoose as a data source. If you decide to use Mongoose in your application, you will definitely read it. Read its out online documentation and learn about it from Mongoose

In this section, we will walk through the basics of mongoose, including how to do the following

  • open and close a MongoDB connection.
  • Register a schema.
  • Add a task.
  • Search for a document.
  • Then update a document,
  • Remove a document.

First, you can install Mongoose via npm using the following command.

npm install mongoose

Opening and Closing a connection

Once you have installed Mongoose and have started your Mongo DB server, the following example, code will establish a MongoDB connection in this case, to a database called tasks.

var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/tasks');

To disconnect the connection, run the following command


Registering a Schema

When managing data using Mongoos, you will need to register a schema. The following code shows, the registration of a schema for tasks.

const { Schema, mongoose } = require('mongoose');
var db = mongoose.connect('mongodb://localhost/tasks');

var schema = mongoose.Schema; 
var tasks = new Schema({
    project: String,
    description: String
mongoose.model('Task', tasks);


Mongoose schemas are powerful in addition to Define data structures. They also allow you to set defaults process input and enforce validation. For more on Mongoose schema definition, visit Mongoose online documentation.

Adding a Task

Once a schema is registered, you can access it and put Mongoose to work. The following code shows how to add a task using a model.

var Task = mongoose.model('Task');
var t = new Task();
t.project = 'AWS';
t.description = "AWS With Atiq"; function (err){
    if(err) throw err ; 
    console.log('Task saved ');

Searching for a document

Searching with Mongoose is similarly easy, the task models, find method allows you to find all documents or to select specific document using a JavaScript object to specify your filtering criteria. The following example, code searches for taxes associated with a specific project and outputs, each taxes, unique, ID, and description.

var Task = mongoose.model('Task');
Task.find({'project':'AWS'}, function(err, tasks ){
    for(var i=0; i< tasks.length; i++ ){
        console.log('ID: '+ tasks[i]._id);
        console.log( tasks[i].description );

Updating a document

Although it’s possible to use some models, find method to zero in on a document that you can subsequently change and save Mongoose models. Also have an update method,

Specially for this purpose. The following snippet shows, how you can update a document using mongoose.

var Task = mongoose.model('Task');
    {_id: '5465344ttwerf94uiweruy'},
    {description: 'AWS withatiq '},
    {multi: false },
    function(err, rows_updated){
        if(err) throw err; 

Removing a document

It’s easy to remove a document in Mongoose once you have retrived it. You can retrieve and remove a document using its internal ID. Using code similar to the Following.

var Task = mongoose.model('Task');
Task.findById('98fweiuh2938hreurewiurksfh', function(err, t ){


You will find much to explore in Bongos. It’s an all-around great tool, that enables you to compare the flexibility and performance of MongoDB, with the ease of use traditionally associated with relational database Management Systems.

Spread the love