How to work Mongojs module in Node.js ?
Last Updated :
09 Mar, 2022
Mongojs module is a built-in module in node.js that facilitates the usage of MongoDB with Node.js. It offers almost all the functionality that is provided by the official API of MongoDB and is used extensively by developers across the globe.
Follow the steps mentioned below to install mongojs module and get it up and running.
Project Setup and Module Installation:
Step 1: You need to install npm and node.js first on your machine.
Step 2: Open the command prompt in the desired project location. You need to create a new NodeJS application project (here, named gfg) and initialize the same. Use the following command:
mkdir gfg && cd gfg
npm init -y
Step 3: Use the following command to install mongojs module:
npm install mongojs
Step 4: Create a file "app.js" in your project location where you will write the core logic of your application.
Project Directory: It will look like this.
Project DirectoryGetting Started with Mongojs Module: The objective here is to create a simple application that lets you store key-value pairs in your MongoDB database and query the same for specific or all entries. Before we begin, make sure you have installed node.js and mongojs correctly as mentioned earlier.
The idea is to include the mongojs module in our project and initialize a DB connection to the same. Then we'll use the 'insert()' method of the mongojs module to insert elements and the 'find()' method to search for specific or all the elements present in our collection.
You can refer to the code below for usage of the mongojs module in your projects. Copy the below code in the app.js file that you created while setting up the project.
Example: Write the below code in the app.js file:
JavaScript
// Include the mongojs module in your project
const mongojs = require("mongojs");
const db = mongojs(
`mongodb+srv://<username>:<password>@cluster0.q2lqx.mongodb.net/
mydb?retryWrites=true&w=majority`,
["mycollection"]
);
// Reports an error if the db cannot
// be initialised properly
db.on("error", function (err) {
console.log("database error", err);
});
// Prints "database connected" in the console
// if the database connection is established
// successfully
db.on("connect", function () {
console.log("database connected");
});
// Insert entries in mongodb database
db.mycollection.insert({ name: "Shruti" });
db.mycollection.insert({ name: "Swati" });
db.mycollection.insert({ name: "Ayushi" });
db.mycollection.insert({ name: "Sanskriti" });
// Query the database for a specific entry
db.mycollection.find({ a: 1 }, function (error, found) {
if (error) {
console.log(error);
} else {
console.log(found);
}
});
// Query the database for all entries
db.mycollection.find({}, function (error, found) {
if (error) {
console.log(error);
} else {
console.log(found);
}
});
Step to run the application: Run the app.js file using the following command:
node app.js
Output: You should see the following output on the terminal screen:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read