MongoDB is the most popular NoSQL database. MongoDB stores data in collections. The individual records in the collections are called documents, which have a key-value structure that is like JSON data. MongoDB is preferred because of its performance, flexibility, and scalability features.
What is Mongoose?
Mongoose is a promise-based Object Data Modeling (ODM) library for the Node.js framework. Mongoose simplifies how you interact with a MongoDB database. It allows you to create and model MongoDB schema. This way, you avoid complex writing of database queries/schemas. Mongoose gives you the ability to model the data you want to store in MongoDB.
This guide will help you understand how to connect MongoDB to Node.js using Mongoose.
Prerequisites
To continue with this guide, ensure
Node.js is installed on your computer.
MongoDB is installed on your computer or a cloud MongoDB Atlas account.
Basic knowledge of creating Node.js servers.
Postman is installed.
Setting the Node.js Mongoose Project
To create a Node.js project, run npm init -y in your desired folder. Then install the following packages:
Express - to create a Node.js HTTP server.
Mongoose - MongoDB ODM for Node.js
npm
install
express mongoose
Establish Mongoose MongoDB Node.js connection
To establish a connection to MongoDB using Mongoose, create a db.js file and connect Mongoose as follows:
Import the Mongoose library:
const mongoose
= require(
'mongoose'
);
The MongoDB used here is running locally. Thus, Mongoose will establish a connection to
mongodb:
//localhost:27017test
, where
test
is your database name. Ensure you enter the correct URI that connects to either the locally installed MongoDB or cloud MongoDB Atlas.
Finally, export the
connectDB
function.
module.exports
= connectDB
;
Create a server.js file to run this function as follows:
Here, we are creating a MySchema function that executes the mongoose.Schema method. This method sets the schema that Mongoose will run to MongoDB. To create the schema, add the files that your document will have. In this case, we are adding two fields:
A name - As the above code inside, this field will be created as a string with a
maxlength
of fifty characters.
required
is set true to indicate that every document being created must have this field.
A createdAt field - Sets the time the document was created. It is executed as a date type created by default with the current date.
Add Data to the Database Using the Mongoose Schema
To add data to the database, create a controller.js file.
Import MySchema from the model file
const Task
= require(
'./model'
);
Add a task to a task collection. This will define the POST route.
1
exports.createTask = async (req, res) => {
try {
// get the task from the bodyconst taskData = await req.body;
//create a new task then saveawait Task.create(taskData)
.then((createdTask) => {
if (!createdTask) return res.status(404)
.json({
success: false,
message: "Task creation failed",
error: "Unable get created task"
res.status(201)
.json({
success: true,
createdTask
.catch((error) => {
res.status(404)
.json({
success: false,
error: error.message
} catch (error) {
res.status(500)
.json({
success: false,
message: "Internal server error"
Retrieve All Tasks
Add this code to the controller.js file. This will define the GET route.
1
exports.createTask = async (req, res) => {
try {
// get the task from the bodyconst taskData = await req.body;
//create a new task then saveawait Task.create(taskData)
.then((createdTask) => {
if (!createdTask) return res.status(404)
.json({
success: false,
message: "Task creation failed",
error: "Unable get created task"
res.status(201)
.json({
success: true,
createdTask
.catch((error) => {
res.status(404)
.json({
success: false,
error: error.message
} catch (error) {
res.status(500)
.json({
success: false,
message: "Internal server error"
exports.getTasks = async (req, res) => {
//get all the data in the model and return it as responsetry {
Task.find()
.then((allTasks) => {
res.status(200)
.json({
success: true,
allTasks
.catch((error) => {
res.status(404)
.json({
success: false,
message: "Cant fined ",
error
} catch (error) {
res.status(500)
.json({
success: false,
message: "Internal server error",
error: error.message
Create Routes
Create routes to execute the above controllers. Create a new file and call it routes.js and add the following code: