How do you create a collection in node js and mongodb?
Mostly all modern-day web applications have some sort of data storage system at the backend. For example, if you take the case of a web shopping application, data such as the price of an item would be stored in the database. Show
The Node js framework can work with databases with both relational (such as Oracle and MS SQL Server) and non-relational databases (such as MongoDB). In this tutorial, we will see how we can use databases from within Node js applications. In this tutorial, you will learn-
Node.js and NoSQL DatabasesOver the years, NoSQL database such as MongoDB and MySQL have become quite popular as databases for storing data. The ability of these databases to store any type of content and particularly in any type of format is what makes these databases so famous. Node.js has the ability to work with both MySQL and MongoDB as databases. In order to use either of these databases, you need to download and use the required modules using the Node package manager. For MySQL, the required module is called “mysql” and for using MongoDB the required module to be installed is “Mongoose.” With these modules, you can perform the following operations in Node.js
For the remaining topics, we will look at how we can work with MongoDB databases within Node.js. Using MongoDB and Node.jsAs discussed in the earlier topic, MongoDB is one of the most popular databases used along with Node.js. During this chapter, we will see How we can establish connections with a MongoDB database How we can perform the normal operations of reading data from a database as well as inserting, deleting, and updating records in a MongoDB database. For the purpose of this chapter, let’s assume that we have the below MongoDB data in place. Database name: EmployeeDB Collection name: Employee Documents { {Employeeid : 1, Employee Name : Guru99}, {Employeeid : 2, Employee Name : Joe}, {Employeeid : 3, Employee Name : Martin}, }
You need a driver to access Mongo from within a Node application. There are a number of Mongo drivers available, but MongoDB is among the most popular. To install the MongoDB module, run the below command npm install mongodb
Code Explanation:
If the above code is executed properly, the string “Connected” will be written to the console as shown below.
var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost/EmployeeDB'; MongoClient.connect(url, function(err, db) { var cursor = db.collection('Employee').find(); cursor.each(function(err, doc) { console.log(doc); }); }); Code Explanation:
Note: – It is also possible to fetch a particular record from a database. This can be done by specifying the search condition in the find() function. For example, suppose if you just wanted to fetch the record which has the employee name as Guru99, then this statement can be written as follows var cursor=db.collection('Employee').find({EmployeeName: "guru99"}) If the above code is executed successfully, the following output will be displayed in your console. Output: From the output,
var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost/EmployeeDB'; MongoClient.connect(url, function(err, db) { db.collection('Employee').insertOne({ Employeeid: 4, EmployeeName: "NewEmployee" }); }); Code Explanation:
If you now check the contents of your MongoDB database, you will find the record with Employeeid of 4 and EmployeeName of “NewEmployee” inserted into the Employee collection. Note: The console will not show any output because the record is being inserted in the database and no output can be shown here. To check that the data has been properly inserted in the database, you need to execute the following commands in MongoDB
The first statement ensures that you are connected to the EmployeeDb database. The second statement searches for the record which has the employee id of 4.
var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost/EmployeeDB'; MongoClient.connect(url, function(err, db) { db.collection('Employee').updateOne({ "EmployeeName": "NewEmployee" }, { $set: { "EmployeeName": "Mohan" } }); }); Code Explanation:
If you now check the contents of your MongoDB database, you will find the record with Employeeid of 4 and EmployeeName of “Mohan” updated in the Employee collection. To check that the data has been properly updated in the database, you need to execute the following commands in MongoDB
The first statement ensures that you are connected to the EmployeeDb database. The second statement searches for the record which has the employee id of 4.
var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost/EmployeeDB'; MongoClient.connect(url, function(err, db) { db.collection('Employee').deleteOne( { "EmployeeName": "Mohan" } ); }); Code Explanation:
If you now check the contents of your MongoDB database, you will find the record with Employeeid of 4 and EmployeeName of “Mohan” deleted from the Employee collection. To check that the data has been properly updated in the database, you need to execute the following commands in MongoDB
The first statement ensures that you are connected to the EmployeeDb database. The second statement searches and display all of the records in the employee collection. Here you can see if the record has been deleted or not. How to build a node express app with MongoDB to store and serve contentBuilding an application with a combination of both using express and MongoDB is quite common nowadays. When working with JavaScript web based applications, one will normally here of the term MEAN stack.
Hence, it’s always good to understand how Node.js and MongoDB work together to deliver applications which interact with backend databases. Let’s look at a simple example of how we can use “express” and “MongoDB” together. Our example will make use of the same Employee collection in the MongoDB EmployeeDB database. We will now incorporate Express to display the data on our web page when it is requested by the user. When our application runs on Node.js, one might need to browse to the URL http://localhost:3000/Employeeid. When the page is launched, all the employee id in the Employee collection will be displayed. So let’s see the code snippet in sections which will allow us to achieve this. Step 1) Define all the libraries which need to be used in our application, which in our case is both the MongoDB and express library. Code Explanation:
Step 2) In this step, we are now going to get all of the records in our ‘Employee’ collection and work with them accordingly. Code Explanation:
Step 3) In this step, we are going to send our output to the web page and make our application listen on a particular port. Code Explanation:
Output: From the output,
Here is the code for your reference var express = require('express'); var app = express(); var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost/EmployeeDB'; var str = ""; app.route('/Employeeid').get(function(req, res) { MongoClient.connect(url, function(err, db) { var cursor = db.collection('Employee').find(); //noinspection JSDeprecatedSymbols cursor.each(function(err, item) { if (item != null) { str = str + " Employee id " + item.Employeeid + ""; } }); res.send(str); db.close(); }); }); var server = app.listen(3000, function() {}); Note: cursor.each maybe deprecated based on version of your MongoDB driver. You can append //noinspection JSDeprecatedSymbols before cursor.each to circumvent the issue. Alternatively, you can use forEach. Below is the sample code using forEach var express = require('express'); var app = express(); var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost/EmployeeDB'; var str = ""; app.route('/Employeeid').get(function(req, res) { MongoClient.connect(url, function(err, db) { var collection = db.collection('Employee'); var cursor = collection.find({}); str = ""; cursor.forEach(function(item) { if (item != null) { str = str + " Employee id " + item.Employeeid + ""; } }, function(err) { res.send(err); db.close(); } ); }); }); var server = app.listen(8080, function() {}); Summary
How do I create a node JS Collection in MongoDB?Steps to Create Collection in MongoDB via Node.. Step 1: Start MongoDB Service. ... . Step 2: Get the base URL to MongoDB Service. ... . Step 3: Prepare the complete URL. ... . Step 4: Create a MongoClient. ... . Step 5: Make connection from MongoClient to the MongoDB Server with the help of URL.. How is a collection created in MongoDB?In MongoDB, you don't need to create collection. MongoDB creates collection automatically, when you insert some document.
How do I create a collection and document in MongoDB?You can create documents in a collection using the MongoDB CRUD Operators in a MongoDB Playground: Use the insertOne() method to insert one document.. Create a connection to a MongoDB deployment.. Activate the connection to the MongoDB deployment.. Open a MongoDB Playground.. How do I create a schema in MongoDB using node JS?import mongoose from 'mongoose'; const Schema = mongoose. Schema; const postSchema = new Schema({ title: { type: 'String', required: true }, content: { type: 'String', required: true }, slug: { type: 'String', required: true } }); let Post = mongoose. model('Post', postSchema);
|