Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

III

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

IT22511 FULL STACK WEB DEVELOPMENT

UNIT 3

Understanding NoSQL and MongoDB – Building MongoDB Environment – User


accounts – Access control – Administering databases – Managing collections
Connectivity.

I Understanding NoSQL and MongoDB

NoSQL stands for Not only SQL. NoSQL Databases are also known as non-relational
databases that don’t require a fixed schema.

Features of NoSQL

➢ NoSQL information bases are largely utilized for BigData and ongoing applications.
➢ NoSQL database processes information in a distributed manner and can oblige
tremendous volumes of data.
➢ is used to refer to a non-SQL or nonrelational database.
➢ It provides a mechanism for the storage and retrieval of data other than the tabular
relations model used in relational databases.
➢ NoSQL database doesn't use tables to store data. It is generally used to store big data and
real-time web applications.

When should NoSQL be used:


1. When a huge amount of data must be stored and retrieved.
2. The relationship between the data you store is not that important
3. The data changes over time and is not structured.
4. Support of Constraints and Joins are not required at the database level
5. The data is growing continuously and you need to scale the database regularly to handle
the data.

Mapping Relational Databases to MongoDB

Collections in MongoDB is equivalent to the tables in RDBMS.


Documents in MongoDB is equivalent to the rows in RDBMS.
Fields in MongoDB is equivalent to the columns in RDBMS.
Fields (key and value pairs) are stored in document, documents are stored in collection
and collections are stored in database.
How a document looks in MongoDB: This row is similar to the row in RDBMS. The only
difference is that it is in JSON format.

MongoDB
MongoDB is a document-oriented NoSQL database system that provides high scalability,
flexibility, and performance. Unlike standard relational databases, MongoDB stores data in
a JSON document structure form. This makes it easy to operate with dynamic and unstructured
data and MongoDB is an open-source and cross-platform database System.
MongoDB data types and corresponding ID number
Type Number
Double 1
String 2
Object 3
Array 4
Binary data 5
Object id 7
Boolean 8
Date 9
Null 10
Regular Expression 11
JavaScript 13
JavaScript (with scope) 15
32-bit integer 16
Timestamp 17
64-bit integer 18
Decimal126 19
Min key -1
Max key 127

II Building MongoDB Environment

Why use MongoDB?


• Fast – Being a document-oriented database, easy to index documents. Therefore
a faster response.
• Scalability – Large data can be handled by dividing it into several machines.
• Use of JavaScript – MongoDB uses JavaScript which is the biggest advantage.
• Schema Less – Any type of data in a separate document.
• Data stored in the form of JSON.
• Simple Environment Setup – Its really simple to set up MongoDB.
• Flexible Document Model – MongoDB supports document-model(tables,
schemas, columns & SQL) which is faster and easier.

Installation Mongodb Environment.

Step 1: Go to the MongoDB Download Center to download the MongoDB Community Server.
Step 2: When the download is complete open the msi file and click the next button in the startup
screen
Step 3: Accept the End-User License Agreement and click the next button.
Step 4: Now select the complete option to install all the program features. Here, if you can want
to install only selected program features and want to select the location of the installation, then
use the Custom option.
Step 5: Select “Run service as Network Service user” and copy the path of the data
directory. Click Next
Step 6: Click the Install button to start the MongoDB installation process.
Step 7: After clicking on the install button installation of MongoDB begins.
Step 8: Now click the Finish button to complete the MongoDB installation process:
Step 9: Now we go to the location where MongoDB installed in step 5 in your system and copy
the bin path
Step 10: Now, to create an environment variable open system properties >> Environment
Variable >> System variable >> path >> Edit Environment variable and paste the copied link
to your environment system and click Ok.
Step 11: After setting the environment variable, we will run the MongoDB server,
i.e. mongod. So, open the command prompt and run the following command
Step 12: Now, Open C drive and create a folder named “data” Inside this folder create another
folder named “db”. After creating these folders. Again open the command prompt and run the
following command: mongod
Now, this time the MongoDB server(i.e., mongod) will run successfully

Starting MongoDB

Once you have installed MongoDB, you need to be able to start and stop thedatabase
engine. The database engine starts by executing the mongod (mongod.exeon Windows)
executable in the
<mongo_install_location>/binlocation. This executable starts MongoDBand begins listening for
database requests on the configured port.

The mongod executable accepts several different parameters that provide methods of
controlling its behavior. For example, you can configure the IP address and port MongoDB
listens on as well as logging and authentication. Table 12.1 provides a list of some of the most
commonly used parameters.

Here is an example of starting MongoDB with a portand dbpathparameters:

mongod –port 28008 –dbpath <mongo_data_location>/data/db

Mongod command-line parameters


Parameter Description

--help, -h Returns basic help and usage text.


--version Returns the version of MongoDB.
--config Specifies a configuration file that contains runtime-configurations.
<filename>,

-f <filename>

--verbose, -v Increases the amount of internal reporting sent to the


console and written to the log file specified by --logpath.
Reduces the amount of reporting sent to the console and logfile.

--port <port> Specifies a TCP port for mongodto listen for client
connections. Default: 27017.
--bind_ip <ipaddress> <path>
--maxConns
<number>
--logpath
Specifies the IP address Specifies the maximum number of simultaneous connections that mongodwill
on which mongod will accept. Max: 20000
bind to and listen for
connections. Default: Specifies a path for the log file. On restart, the log file isoverwritten unless you
All Interfaces also specify --logappend.

--auth Enables database authentication for users connecting from


remote hosts.
--dbpath Specifies a directory for the mongodinstance to store itsdata.
<path> Disables the HTTP interface.
--
nohttpinterface

--nojournal Disables the durability journaling.

--noprealloc Disables the preallocation of data files, which shortens the


startup time but can cause significant performance penaltiesduring normal operations.
--repair Runs a repair routine on all databases.
Each platform has different methods of stopping the mongodexecutable once it hasstarted. However, one of
the best methods is to stop it from the shell client because that cleanly shuts down the current operations and
forces the mongodto exit.

To stop the MongoDB database from the shell client, use the following commands toswitch to the admin database
and then shut down the database engine:

Useadmin
db.shutdownServer()

Accessing MongoDB from the Shell Client

Once you have installed, configured, and started MongoDB, you can access it through the MongoDB
shell. The MongoDB shell is an interactive shell provided with MongoDB that allows you to access, configure,
and administer MongoDB databases, users, and much more. You use the shell for everything from setting up
user accounts to creating databases to querying the contents of the database.

The following sections take you through some of the most common administration tasks that you perform in
the MongoDB shell. Specifically, you need to be able to create user accounts, databases, and collections to
follow the examples in the rest ofthe book. Also you should be able to perform at least rudimentary queries
on documents to help you troubleshoot any problems with accessing data.

To start the MongoDB shell, first make sure that mongod is running, and then run the mongodcommand, then
execute the mongocommand from the console prompt.The shell should start up as shown in Figure 12.1.

Figure 12.1 Starting the MongoDB console shell

Once you have accessed the MongoDB shell, you can administer all aspects of MongoDB. There are a couple
of things to keep in mind when using MongoDB. First is that it is based on JavaScript and most of its syntax is
available. Second, theshell provides direct access to the database and collections on the server so changesyou
make directly impact the data on the server.

Understanding MongoDB Shell commands

The MongoDB shell provides several commands that can be executed from the shellprompt. You need to be
familiar with these commands as you will use them a lot.
The following list describes each command and its purpose:

• help <option>: Displays syntax help for MongoDB shell commands. The option argument allows you to
specify an area where you want help.
• use <database>: Changes the current database handle. Database operations are processed using the
current database handle.
• db. help: Displays help options for the database methods.
• show <option>: Shows a list based on the optionargument. The value of an optioncan be:
• dbs: Displays a list of databases.
• collections: Displays a list of collections for the current database.
• profile: Displays the five most recent systems. profileentries taking more than 1 millisecond.
• databases: Displays a list of all available databases.
• roles: Displays a list of all roles for the current database, both built-in anduser-defined.
• users: Displays a list of all users for that database.
• exit: Exits the database.

Understanding MongoDB Shell Methods

The MongoDB shell also provides a number of methods to perform administrative functions. These methods
can be called directly from the MongoDB shell or from ascript executed in the MongoDB shell.

There are many methods that you can use to perform various administrative functions. Some of these are
covered in later sections and chapters in this book. Fornow, you need to be aware of the types of shell methods
and how to access them.
The following list provides a few examples of shell methods:

• load(script): This function loads and runs a JavaScript file inside the shell. It is a great way to script
database operations.
• UUID(string): Converts a 32-byte hex string into a BSON UUID.
• db.auth(username, password): Authenticates you to the currentdatabase.

III MongoDB (User Accounts –Access Control)

Creating users and assigning roles in MongoDB is essential for managing access control and securing
your databases. MongoDB provides flexibility in defining user privileges through roles, allowing users
to perform specific operations on designated resources.
How to Create user and add a role in MongoDB???
In MongoDB, users are created using createUser() method.
user: It contains authentication and access information about the user to create. It is a
document.
• user: Name of the user
• pwd: User passw ord. This field is not required if you use this method on $external
database to create a user whose credentials are stored externally. The value of this field
can be of string type or passwordPrompt().
• customData: User Associative Information. It is an optional field.
• roles: Access Level or Privilege of a user. You can also create a user without roles by
passing an empty array[].
writeConcern: It is an optional parameter. It manages the level of Write Concern for the creation
operation.
Create An Administrative User
We can create the name, password, and administrative user roles.

db.createUser(
{
user: "hello_admin",
pwd: "hello123",
roles:
[
{ role:"readWrite",db:"config"},
"clusterAdmin"
] } );

Create A Normal User Without Any Roles

In MongoDB, we can create a user without any roles by specifying an empty array[] in the role field in
the createUser() method.
Syntax:
db.createUser({ user:”User_Name”, pwd:”Your_Password”, roles:[]});

Create A User with Some Specifying Roles

In MongoDB, we can create a user with some specified roles using the createUser() method. In this
method, we can specify the roles that the user will do after creating.
Let us discuss this concept with the help of an example:
Example:
In this example, we are going to create a user with some specified roles.

Create A User For A Single Database


In MongoDB, we can also create a user for single database using the createUser() method.

Create A User With Authentication Restrictions


In MongoDB, authentication is a process which checks whether the user/client who is trying to access the
database is known or unknown. If the user is known then it allows them to connect with server.

db.createUser(
{
user: "restrict",
pwd: passwordPrompt(),
roles: [ { role: "readWrite", db: "example" } ],
authenticationRestrictions: [ {
clientSource: ["192.168.65.10"],
serverAddress: ["198.157.56.0"]
}]
}
)

Creating a Database and Collection in MongoDB

Step 1: Create a Database In MongoDB

Step 2: Create a Collection in MongoDB


Step 3: Insert Documents in Collection in MongoDB
o insertOne()
o insertMany()
Step 4: View Existing Collections

View all the Existing Databases


To view all existing databases in MongoDB use the “show dbs” command.
Syntax

show dbs

How To Drop A User?


In Mongodb, we can also drop a user using dropUser() method. This method returns true when the user
is deleted otherwise return false.
Syntax:
db.dropUser(“Username”)

Querying the data in MongoDB


Step 1: Create collection and Insert documents using Mongo Shell.
Step 2: Select All Documents in a Collection
To select all documents in the collection, pass an empty document as the query filter parameter to the find
method. This statement is similar to the SELECT * FROM table statement in MySQL.

Step 3: Specify Equality Condition


To filter the result of db.collection_name.find() method you need to specify conditions for method.

Step 4: Specify Conditions Using Query Operators


A query filter document can use the query operators to specify a condition.
1. ‘in’ Operator ($in): The following example retrieve all documents which status value is “C” or “B”.

MongoDB – Query Documents using Mongo Shell

If you want to get data in a structured form, then use pretty() method with find() method.
db.collection.find().pretty()

Step 2: Create a Collection in MongoDB


To create a collection in MongoDB use the createCollection() method. Collection name is passed as argument
to the method.
Syntax
db.createCollection(‘ collection_name’ );
Example
Creating collection named “Student” in MongoDB
db.createCollection('Student');
Step 3: Insert Documents in Collection in MongoDB
We can insert documents in the collection using the two methods:
• insertOne()
• insertMany()
1.insertOne() Method
• insertOne() method is used to insert only one document in the collection.
• Example:
• db.myNewCollection1.insertOne( { name:"geeksforgeeks" } )

2. insertMany() method
insertMany() method is used to insert many documents in the collection

Step 4: View Existing Collections


To view all existing collections in a MongoDB database use the “show collection command“:

How to Enable Access Control & Authentication in MongoDB


Access Control and User Authentication is the first step to safe data in the database from external access
without authority.

Steps to Enable Access Control and Authentication in MongoDB


Step 1: Start the MongoDB
To make changes in MongoDB, we need to start the MongoDB server. To start MongoDB, open the command
prompt on our computer and execute the following command to start MongoDB.
mongosh

Step 2: Create Document


use mydb //Creates database
db.createCollection("nameColletion")
Insert few documents into the database.
db.nameCollection.insertOne({ name: "Philips Kumar", age: 21})
Step 4: Change MongoDB Configuration
By default, in MongoDB the authentication feature is not enable. So, to use authentication we first have
to edit the configurations and enable access control. To do that, navigate to the mongod.conf file. The path to
the file should be similar to the following,

Open the mongod.conf file in any editor and write the following under security,
Save the changes and close the file. Once we have made the changes, Go to Services in Windows and
find MongoDB and restart it.

Step 3: Create User


To use authentication, we need to define a user and assign certain role to it. Lets create a user named Geek and
assign the role of useradmin for the database mydb. The useradmin role provides the user with power
to create new users and assign roles to others including self. This user can access, update or delete any data
in the database. If short, we are giving the superuser role to the user named Geek. However, The privileges of
the user stays only inside the database defined.

db.createUser({
... "user": "Geek",
... "pwd": "abc123",
... "roles": [ { "role": "userAdmin", "db": "mydb" } ]
... })

we need to authenticate first to get the data. That means we have successfully enabled authentication
and access control.
let’s first give the username and password.
db.auth("Geek","abc123")
db.nameCollection.find()

MongoDB CRUD Operations


CRUD Operations (Create, Read, Update, and Delete) are the basic set of operations that allow users to interact
with the MongoDB server.
1. Create Operations
The create or insert operations are used to insert or add new documents in the collection. If a collection does
not exist, then it will create a new collection in the database.
You can perform, create operations using the following methods provided by the MongoDB.

Method Description

db.collection.insertOne() It is used to insert a single document in the collection.

db.collection.insertMany() It is used to insert multiple documents in the collection.

db.createCollection() It is used to create an empty collection.


2. Read Operations
The Read operations are used to retrieve documents from the collection, or in other words, read operations are
used to query a collection for a document.
You can perform read operation using the following method provided by the MongoDB.

Method Description

db.collection.find() It is used to retrieve documents from the collection.

3. Update Operations
The update operations are used to update or modify the existing document in the collection. You can perform
update operations using the following methods provided by the MongoDB.
Method Description

It is used to update a single document in the collection that satisfy


db.collection.updateOne()
the given criteria.

It is used to update multiple documents in the collection that satisfy


db.collection.updateMany()
the given criteria.

It is used to replace single document in the collection that satisfy


db.collection.replaceOne()
the given criteria.

4. Delete Operations
The delete operation are used to delete or remove the documents from a collection. You can perform delete
operations using the following methods provided by the MongoDB.

Method Description

It is used to delete a single document from the collection that satisfy


db.collection.deleteOne()
the given criteria.

db.collection.deleteMany() It is used to delete multiple documents from the collection that


satisfy the given criteria.

How to Connect Node to a MongoDB Database?

Steps to Connect Node to a MongoDB Database

Step 1: Install mongoose in your system using the below command.


Step 2: Import the mongoose library
To connect a Node.js application to MongoDB, we have to use a library called Mongoose.
const mongoose = require("mongoose");
Step 3: Use the Mongoose connect method to establish the connection
mongoose.connect("mongodb://localhost:27017/collectionName", {
useNewUrlParser: true,
useUnifiedTopology: true
});
Then we have to define a schema. A schema is a structure, that gives information about how the data is being
stored in a collection.
Step 4: Define the Schema
Example: Suppose we want to store information from a contact form of a website.

const contactSchema = {
email: String,
query: String,
};
Step 5: Create a Model with the defined schema
const Contact = mongoose.model("Contact", contactSchema);
app.post("/contact", function (req, res) {
const contact = new Contact({
email: req.body.email,
query: req.body.query,
});
contact.save(function (err) {
if (err) {
res.redirect("/error");
} else {
res.redirect("/thank-you");
}
});
});
const express = require("express"); {
const ejs = require("ejs"); res.render("contact");
const mongoose = require("mongoose"); });
const bodyParser = require("body-parser"); app.post("/contact",
mongoose.connect( function (req, res) {
"mongodb://localhost:27017/newCollection", console.log(req.body.email);
{ const contact = new Contact({
useNewUrlParser: true, email: req.body.email,
useUnifiedTopology: true query: req.body.query,
}); });
const contactSchema = { contact.save(function (err) {
email: String, if (err) {
query: String, throw err;
}; } else {
const Contact = res.render("contact");
mongoose.model("Contact", contactSchema); }
const app = express(); });
app.set("view engine", "ejs"); });
app.use(bodyParser.urlencoded({ app.listen(3000,
extended: true function () {
})); console.log("App is running on Port 3000");
app.use(express.static(__dirname + '/public')); });
app.get("/contact",
function (req, res)

IV Administering databases.
Database administration in MongoDB involves managing the MongoDB environment to ensure
optimal performance, security, and reliability. Key aspects of administering a MongoDB database
include:
1. User Management and Access Control
• User Creation: Admins can create users with specific roles and permissions using commands
like db.createUser().
• Role-Based Access Control (RBAC): MongoDB employs RBAC, allowing administrators to
define roles that dictate what actions users can perform on the database (e.g., read, write,
dbAdmin).
2. Database Backup and Restore
• Backup: Administrators can back up data using tools like mongodump for logical backups or file
system snapshots for physical backups.
• Restore: The mongorestore command is used to restore data from backups, ensuring data
integrity during recovery.
3. Performance Monitoring and Tuning
• Monitoring Tools: MongoDB provides tools like the MongoDB Atlas performance monitoring,
as well as the mongostat and mongotop commands for real-time statistics.
• Indexing: Effective indexing strategies can significantly enhance query performance. Admins
must regularly review and optimize indexes based on query patterns.
4. Replication and High Availability
• Replica Sets: Admins can configure replica sets to ensure high availability and data redundancy.
A replica set consists of a primary node and one or more secondary nodes.
• Automatic Failover: In the event of a primary node failure, MongoDB automatically promotes a
secondary node to primary, ensuring continuous data availability.
5. Sharding for Scalability.
• Sharding: MongoDB supports sharding, which distributes data across multiple servers to handle
large datasets and high throughput. Admins define shard keys to efficiently partition data.
6. Data Management and Maintenance
• Data Modeling: Effective schema design is crucial for performance. Admins should consider
data relationships, access patterns, and document size when modeling data.
• Data Migration: MongoDB provides tools and commands (like mongoimport and mongoexport)
for importing and exporting data between different MongoDB instances.
V Managing collections Connectivity.
Managing Collections

As a database admin, you may also find yourself administering collections within a database. MongoDB
provides the functionality in the MongoDB shell to create, view, and manipulate collections in a database.
The following sections cover the basics that you need to know to use the MongoDB shell to list collections,
create new ones, and access the documents contained within them.

Displaying a List of Collections in a Database

Often you may need to just see a list of collections contained in a database—for example, to verify that a
collection exists or to find the name of a collection that you cannot remember. To see a list of collections in a
database, you need to switch to that database and then use show collections to get the list of collections
containedin the database. For example, the following commands list the collections in the test database:
use test
show collections

Creating Collections

You must create a collection in MongoDB database before you can begin storing documents. To create a
collection, you need to call createCollection(name,[options])on the database handle. The nameparameter is the
name of the new database. The optional optionsparameter is an object that can have the propertieslisted in Table
12.4 that define the behavior of the collection.
Table 12.4 Options that can be specified when creating collectionsRole Description
A Boolean; when true, the collection is a capped collection that does not grow bigger than the maximum
size specified by the sizeattribute. Default: false.
A Boolean; when true, an _id field is automatically created for each document addedto the collection and an
index on that field is implemented. This should be falseforcapped collections. Default: true.
Specifies the size in bytes for the capped collection. The oldest document is removed tomake room for new
documents.
Specifies the maximum number of documents allowed in a capped collection. The oldest document is
removed to make room for new documents.
Allows users to specify validation rules orexpressions for the collection.
validationLevel Determines the strictness MongoDB applies to

the validation rules on documents duringupdates.

validationAction Determines whether an invalid document is


errored or warned but still can be inserted.
indexOptionDefaults Allows users to specify a default index
configuration when a collection is created.

For example, the following lines of code create a new collection callednewCollectionin the testDBdatabase as
shown in Figure 12.7:

db.createCollection("newCollection")

Figure 12.7 Creating a new collection in the MongoDB console shell

Deleting Collections

Occasionally you also want to remove old collections when they are no longer needed. Removing old
collections frees up disk space and eliminates any overheadsuch as indexing associated with the collection.

To delete a collection in the MongoDB shell, you need to switch to the correct database, get the collection object,
and then call the drop() function on that object. For example, the following code deletes the newCollection
collection from the testDBdatabase as shown in Figure 12.8:

use testDB
show collections
coll = db.getCollection("newCollection")coll.drop()
show collections
Figure 12.8 Deleting a collection in the MongoDB console shell

Finding Documents in a Collection

Most of the time you use a library such as the native MongoDB driver or Mongooseto access documents in a
collection. However, sometimes you might need to look atdocuments inside the MongoDB shell.

The MongoDB shell provides full querying functionality to find documents in collections using the find(query)
method on the collection object. The optionalquery parameter specifies a query document with fields and
values to match documents against in the collection. The documents that match the query are removed from
the collection. Using the find() method with no query parameter returns all documents in the collection.

For example, the following lines of code first query every item in the collection and then retrieve the
documents whose speedfield is equal to 120mph. The results areshown in Figure 12.9.

use testDB
coll = db.getCollection("newCollection")coll.find()
coll.find({speed:"120mph"})

Figure 12.9 Finding documents in a collection

Adding Documents to a Collection

Typically, the insertion of documents in a collection should be done through your Node.js application.
However, at times you may need to manually insert a document from an administrative point of view to
preload a database, to fix a database, or for testing purposes.

To add documents to a collection, you need to get the collection object and then callthe insert(document) or
save(document) method on that object. The document parameter is a well-formatted JavaScript object that is
converted to BSON and stored in the collection. As an example, the following commands create three new
objects inside a collection as shown in Figure 12.10:

use testDB
coll = db.getCollection("newCollection")coll.find()
coll.insert({ vehicle: "plane", speed: "480mph" })coll.insert({ vehicle: "car", speed:
"120mph" }) coll.insert({ vehicle: "train", speed: "120mph" })coll.find()

Figure 12.10 Creating documents in a collection

Deleting Documents in a Collection

Deletion of documents in a collection also is typically done through your Node.js application. However, at
times you may need to manually remove a document froman administrative point of view to fix a database or
for testing purposes.

To remove documents from a collection, you need to get the collection object and then call the remove(query)
method on that object. The optional query parameter specifies a query document with fields and values to
match documents against in the collection. The documents that match the query are removed from the
collection. Using the remove() method with no query parameter removes all documents in the collection. As
an example, the following commands first remove documents where the vehicle is plane and then all
documents from the collection, asshown in Figure 12.11:

use testDB
coll = db.getCollection("newCollection")coll.find()
coll.remove({vehicle: "plane"})coll.find()
coll.remove()
coll.find()

Figure 12.11 Deleting documents from a collection

Updating Documents in a Collection

Updates of documents in a collection should also be done through your Node.js application. However, at
times you may need to manually update a document froman administrative point of view to fix a database or
for testing purposes.

To update documents in a collection, you need to get the collection. Then you can use a couple of different
methods: The save(object)method saves changes thatyou have made to an object, and the update(query,
update, options) method queries for documents in the collection and then updates them as they are found.

When using the update() method, the query parameter specifies a query document with fields and values to
match documents against in the collection. The update parameter is an object that specifies the update
operator to use when making the update. For example, $incincrements the value of the field, $setsetsthe value
of the field, $push pushes an item onto an array, and so on. For example, the following update object
increments one field, sets another, and then renames a third:

{ $inc: {count: 1}, $set: {name: "New Name"}, $rename: {"nickname": "al

The optionsparameter of update()is an object that has two properties


—multiand upsert—that are both Boolean values. If upsertis true, a new document is created if none are
found. If multiis true, all documents that matchthe query are updated; otherwise, only the first document is
updated.

Steps to Connect Node to a MongoDB Database

Connecting MongoDB to a Node.js application allows developers to create robust, data-driven


applications. This connection can be achieved using the popular library Mongoose, which provides a
schema-based solution to model application data.
ensure that you have the following installed:
• Node.js: Download and install from Node.js Official Website.

• MongoDB: Download and install from MongoDB Community Edition.


• npm: (Node Package Manager, which comes with Node.js).
2. Set Up Your Project
1. Create a New Directory for Your Project:
mkdir mongo-node-app
cd mongo-node-app
2. Initialize a New Node.js Project:
npm init -y
3. Install Required Packages: Install Mongoose and Express (optional, for creating a web server):
npm install mongoose express
3. Start MongoDB
Before connecting your Node.js application to MongoDB, ensure that the MongoDB server is
running. You can start MongoDB using:
mongod
If you have installed MongoDB as a service, you can start it using:
net start MongoDB
4. Create a Connection to MongoDB
1. Create an index.js File: In your project directory, create a file named index.js.
2. Set Up the Connection Using Mongoose: Below is the code to connect to your MongoDB
instance:
// index.js
const mongoose = require('mongoose');
const express = require('express');
const app = express();
// Middleware to parse JSON
app.use(express.json());

// Replace the connection string with your MongoDB URI


const mongoURI = 'mongodb://localhost:27017/mydatabase';

// Connect to MongoDB
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('MongoDB connected successfully');
})
.catch(err => {
console.error('MongoDB connection error:', err);
});

// Define a sample schema and model


const UserSchema = new mongoose.Schema({
name: String,
age: Number
});
const User = mongoose.model('User', UserSchema);
// Sample route to test connection
app.get('/', (req, res) => {
res.send('Welcome to MongoDB with Node.js!');
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
5. Run Your Application
1. Start Your Node.js Application: In the terminal, run:
node index.js
2. Verify the Connection: Check the console output. You should see:
MongoDB connected successfully
Server is running on port 3000
6. Testing the Connection
Open a web browser or use a tool like Postman to test the connection by navigating to:
http://localhost:3000/
You should see the message:
Welcome to MongoDB with Node.js!

You might also like