I am Mikhail Evdokimov, a Hobbyist Self Taught Programmer
Connect, Save and Find Data in MongoDB with NodeJS and ExpressJS
July
17th,
2016
In this article I’ll tell you about how to connect to the MongoDB using NodeJS with Mongoose and MongoDB drivers. As well as Save data and Find data in MongoDB.
For work on this post You need to install NodeJS and MongoDB
There is also a MongoDB driver, I’ll tell you about it in this article, but I prefer to use the Mongoose because it provides the opportunity to create the database schema
After successful install packages, in project folder create server.js file and in your terminal or command prompt run MongoDB with mongod command.
Use Mongoose Driver
server.js
Let’s analyze this code for details
On lines 1 — 6 we include all the necessary dependencies
On lines 7 — 12 create database schema
At the end of this article I will show how to use mongodb command line to access the data
On lines 14 and 15 create model and connect to MongoDB
If you decide to use mLab just replace mongodb://localhost:27017/dbName with database URL. For example:
On lines 18 — 31 is implemented a route which we will use to insert data to the database
Here, to variable query input request /:query which then stored to a database into request key
Then, if you save the data error has occurred, you will receive an error on the console. If all goes successful you will see the stored data in JSON format on the page.
On lines 33 — 48 has a function find for search data in database. In request key
As in a save function, request is recorded to query variable /:query then passed to the function find to search
If an error occurs when you search you will see it in the console. If all goes correctly you will get all the documents in JSON format containing the current query in request key
Finally we create a server
Usage
To save you can just go in your browser to the following URL
For use find you can just go to the browser to the following URL
where :query it’s your request for find. Example:
Output
Use MongoDB Driver
First, Install mongodb driver with npm install mongodb. And replace code in your server.js file with:
Quickly analyze that code
MongoDB Driver
Connect and create collection
Save
Find
MongoDB Command Line Interface
Open another terminal and run the command mongo to open MongoDB CLI
To see a list of existing databases, use the command show dbs
In this article, as the database name I used a dbName. To use this database, run the command use dbName
Show collections with show collections
We see that in the database dbName have a collection named collectionName which contains our data. Let’s read this data using the command db.collectionName.find().pretty()