Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

MongoDBNode JS
Home›Database›MongoDB›Using MongoDB on Node JS Application Using Mongoose

Using MongoDB on Node JS Application Using Mongoose

By SibeeshVenu
December 3, 2017
4041
0
Share:
MongoDB Data Insertion

[toc]

Introduction

In this post, we are going to see how we can use a MongoDB on our Node JS application with the help of the package Mongoose. We will also be covering some facts about MongoDB so that as a reader, you will understand why we had chosen MongoDB as our backend. We will be going through some steps to install the required packages using a node package manager terminal, so please be with me. At the end of this article, I guarantee that you will be proficient on how to connect a MongoDB in our Node JS application. I hope you will like this article.

Why MongoDB?

Here, I am going to list down the reasons why I had chosen MongoDB.

  1. MongoDB is a NoSQL database when I say NoSQL, it means that it doesn’t have any structure to be followed.
  2. There are no relationships, we can perform the relation using separate packages like Mongoose
  3. Everything is JSON, even the data and collections are stored as JSON
  4. Since the data is stored as JSON, no more conversions are needed. We can directly use it in our application.

Source Code

You can always clone or download the source code here

Background

Node JS has become a trend now, thus some most used databases. One of the recommended database for a Node application is MongoDB. As we discussed a MongoDB doesn’t have any structure inbuilt, here we are going to use a package called Mongoose, with that we can create some structure for our Database. Let’s just skip the talking and start developing.

Setting up Node application

To get started with the Node JS, create a folder and name as per your wish, this is going to be our project directory. Here I am going to use one of my favorite editor, Visual Studio Code. Now please point to your project container, and run the command below.

npm init
NPM Init

NPM Init

This will create a file named “Package.json” in your directory. We will be adding all of our dependencies in this file very soon. The command may ask you some default questions which you need to answer. If you need to create the package.json file with default values in it, you may consider running the below command.

npm init --yes

Let’s review our package.json file.

{
  "name": "node-mongodb-mongoose",
  "version": "1.0.0",
  "description": "A Node application with MongoDB and Mongoose",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "Node",
    "Mongoose",
    "MongoDB"
  ],
  "author": "Sibeesh Venu",
  "license": "ISC"
}

Getting the required packages

Now that we have the application ready, let’s get the required packages ready.

npm install --save mongoose

This will create a new folder npm_modules on your project directory where you can see the package Mongoose in it.

npm install --save express

The above command will add the package express to our application.

Creating the Node App

Now we can create our server.js file where we are going to write most of our application code.

var express = require("express")
var app = express()
app.listen("3010",()=>{
    console.log("I just started listening!.")
})

Now run the command node server.jsand make sure that you are getting a console as ” I just started listening!.”.

If you are getting an error as preceding, please make sure that you are running the application on an unused port.

PS F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose> node server.js
events.js:136
throw er; // Unhandled ‘error’ event
^

Error: listen EADDRINUSE :::3000
at Object._errnoException (util.js:1031:13)
at _exceptionWithHostPort (util.js:1052:20)
at Server.setupListenHandle [as _listen2] (net.js:1367:14)
at listenInCluster (net.js:1408:12)
at Server.listen (net.js:1496:7)
at Function.listen (F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose\node_modules\express\lib\application.js:618:24)
at Object.<anonymous> (F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose\server.js:3:5)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
at Module.load (module.js:560:32)”

Setting up database

Now that we have our application ready, let’s go and create our database. I am going to use mLab for creating the database. If you have not installed MongoDB on your machine, I strongly recommend creating a database in mLab. I had created a database there and have got my connection string as preceding.

mongodb://<dbuser>:<dbpassword>@ds038319.mlab.com:38319/mylearning

We will be updating the connection string with actual DB user and password later. Please make sure that you are creating a user for your DB and remember the password.

Creating a Mongoose model

Let’s create a Mongoose model and set up our connection string now, which is going to be our collection. No worries, it is just a JavaScript model.

var conString = "mongodb://admin:admin@ds038319.mlab.com:38319/mylearning"

/**
 * Models 
 */
var User = mongoose.model("User", {
    firstName: String,
    lastName: String
})

Please be noted that, when you move the codes to production, make sure that your password and user fields on the connection string are separated from this file and encrypted

Now let’s connect our database.

mongoose.connect(conString, { useMongoClient: true }, () => {
    console.log("DB is connected")
})

Setup the data

We have our model ready, what else is needed now? Yes, you are right, we need data.

var dummyUser = {
    firstName: "Sibeesh",
    lastName: "Venu"
}

Inserting the data into MongoDB

We have got everything ready, we can insert the model now. Let’s do the saving logic now.

mongoose.connect(conString, { useMongoClient: true }, () => {
    console.log("DB is connected")
    saveData()
})
function saveData() {
    var user = new User(dummyUser);
    user.save();
}

Verify the data

Once you run your application, go to your database and check for the entries there. I am sure there will be a new collection “User” and our inserted data. As I am using mLab database, here is how my data saved.

MongoDB Data Insertion

MongoDB Data Insertion

If you have noticed, you can see there are an another property names “_id” in our database collection. This is a unique id generated by MongoDB for us, so no need to think about it.

Todo

As the purpose of this article is to show how we can insert a data to MongoDB, I called the save method right after the database is connected. In our real life, this is not a recommended way. You must create an Ajax post request and handle the same. I am leaving that task to you. Please try to do that and let me know. I would love to hear back from you.

Conclusion

Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Kindest Regards
Sibeesh Venu

TagsEasy way to insert data to MongoDBMongoDBMongoDB with MongooseMongooseNode JSNode JS and MongoDBNPM
Previous Article

Implement Validations in Angular 5 App

Next Article

Creating a Chat Application in Node JS ...

0
Shares
  • 0
  • +
  • 0
  • 0
  • 0

SibeeshVenu

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

Related articles More from author

  • npm-npx
    npm

    npm vs npx

    October 20, 2018
    By SibeeshVenu
  • MongoDB

    Learn MongoDB With Me

    February 22, 2018
    By SibeeshVenu
  • node_js_tool_for_visual_studio
    Node JSSQL

    SQL Server CRUD Actions Using Node JS

    November 27, 2016
    By SibeeshVenu
  • Node JS

    Introduction to Node JS

    June 19, 2015
    By SibeeshVenu
  • Container Instance Basic Settings
    AzureDocker

    Having a Docker Container as Your Private NPM Registry – The Easy Way

    November 10, 2018
    By SibeeshVenu
  • MongoDB

    Continue With Learning Indexes in MongoDB

    March 7, 2018
    By SibeeshVenu
0

My book

Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

YouTube

MICROSOFT MVP (2016-2022)

profile for Sibeesh Venu - Microsoft MVP

Recent Posts

  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
  • Easily move data from one COSMOS DB to another
  • .NET 8 New and Efficient Way to Check IP is in Given IP Range
  • Async Client IP safelist for Dot NET
  • Post Messages to Microsoft Teams Using Python
  • Get Azure Blob Storage Blob Metadata Using PowerShell
  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
  • Integrate Azure App Insights in 1 Minute to .Net6 Application
  • Azure DevOps Service Connection with Multiple Azure Resource Group

Tags

Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
  • .NET
  • Achievements
  • ADO.NET
  • Android
  • Angular
  • Arduino
  • Article Of The Day
  • ASP.NET
  • Asp.Net Core
  • Automobile
  • Awards
  • Azure
  • Azure CDN
  • azure devops
  • Blockchain
  • Blog
  • Browser
  • C-Sharp Corner
  • C#
  • Career Advice
  • Code Snippets
  • CodeProject
  • Cognitive Services
  • Cosmos DB
  • CSS
  • CSS3
  • Data Factory
  • Database
  • Docker
  • Drawings
  • Drill Down Chart
  • English
  • Excel Programming
  • Exporting
  • Facebook
  • Fun
  • Gadgets
  • GitHub
  • GoPro
  • High Map
  • HighChart
  • How to
  • HTML
  • HTML5
  • Ignite UI
  • IIS
  • Interview
  • IoT
  • JavaScript
  • JQuery
  • jQuery UI
  • JQWidgets
  • JQX Grid
  • Json
  • Knockout JS
  • Linux
  • Machine Learning
  • Malayalam
  • Malayalam Poems
  • MDX Query
  • Microsoft
  • Microsoft ADOMD
  • Microsoft MVP
  • Microsoft Office
  • Microsoft Technologies
  • Microsoft Windows
  • Microsoft Windows Server
  • Mobile
  • MongoDB
  • Monthly Winners
  • MVC
  • MVC Grid
  • MySQL
  • News
  • Node JS
  • npm
  • Number Conversions
  • October 2015
  • Office 365
  • Office Development
  • One Plus
  • Outlook
  • Page
  • PHP
  • Poems
  • PowerShell
  • Products
  • Q&A
  • Raspberry PI
  • React
  • SEO
  • SharePoint
  • Skype
  • Social Media
  • Software
  • Spire.Doc
  • Spire.PDF
  • Spire.XLS
  • SQL
  • SQL Server
  • SSAS
  • SSMS
  • Storage In HTML5
  • Stories
  • Third Party Software Apps
  • Tips
  • Tools
  • Translator Text
  • Uncategorized
  • Unit Testing
  • UWP
  • VB.Net
  • Videos
  • Virtual Machine
  • Visual Studio
  • Visual Studio 2017
  • Wamp Server
  • Web API
  • Web Platform Installer
  • Webinars
  • WebMatrix
  • Windows 10
  • Windows 7
  • Windows 8.1
  • Wordpress
  • Writing

ABOUT ME

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

Contact Me

  • info@sibeeshpassion.com

Pages

  • About
  • Search
  • Privacy Policy
  • About
  • Search
  • Privacy Policy
© Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
Go to mobile version