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
How to Use MongoDB and Mongoose with Node.js ? MongoDB is a popular NoSQL database that offers flexibility and scalability, making it an excellent choice for modern applications. Mongoose, a powerful ODM (Object Data Modeling) library, simplifies the interaction between MongoDB and Node.js by providing a schema-based solution for data validation
6 min read
What are Modules in Node.js ? In Node.js Application, a Module can be considered as a block of code that provide a simple or complex functionality that can communicate with external application. Modules can be organized in a single file or a collection of multiple files/folders. Almost all programmers prefer modules because of t
5 min read
What are modules in Node JS ? In NodeJS, modules are encapsulated units of code that can be reused across different parts of an application. Modules help organize code into smaller, manageable pieces, promote code reusability, and facilitate better maintainability and scalability of NodeJS applications. Types of Modules:Core Mod
2 min read
How To Create Modules in NodeJS? Modules are the building blocks of NodeJS code. They help you break down your project into smaller, manageable pieces, each with its own job.To create a module, just make a JavaScript file and export what you want to share. Other files can then import and use those exports, adding that functionality
3 min read
How does Query.prototype.mod() work in Mongoose? The Query.prototype.mod() function is used to specify a $mod condition. This function basically filters documents for documents whose path property is a number that is equal to remainder modulo divisor. Syntax:  Query.prototype.mod() Parameters: This function has one optional path parameter and an
2 min read
How to Use MongoDB Transactions in Node.js? Using MongoDB transactions in Node.js involves several steps. Transactions allow multiple operations on the database to be executed in an all-or-nothing manner, ensuring data consistency. we will learn how to use MongoDB transaction in Node.js.PrerequisitesMongoDB (Version 4.0 or higher Recommended)
2 min read