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.
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.
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.
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
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');
Create a connectDB
as follows:
1
2
3
4
5
6
7
8
9
10
11
const connectDB = async () => {
try {
const conn = await mongoose.connect(`mongodb://localhost:27017/test`, {
useNewUrlParser: true,
});
console.log(`MongoDB Connected: {conn.connection.host}`);
} catch (error) {
console.error(error.message);
process.exit(1);
}
}
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:
import Express and db.js file:
1 2
const express = require('express'); const connectDB = require('./db');
Add Express middleware and parser:
1 2 3 4
// express const app = express(); //body parser app.use(express.json());
Execute the connectDB() function:
1 2
//connect to database connectDB();
Add server routes:
1 2
// routes // We will add these routes later in this guide.
Run the application on a local host port:
1
2
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port {PORT}`));
To test this setup, run node server.js. This should log the following message if a connection to the database was established successfully.
A model defines a collection schema inside a MongoDB database. Create a model.js file and a Mongoose collection schema as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const {
Schema,
model
} = require("mongoose");
const MySchema = new Schema({
name: {
type: String,
required: true,
maxlength: 50
},
createdAt: {
type: Date,
default: Date.now,
},
});
const TaskModel = model("test", MySchema)
module.exports = TaskModel
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.
To add data to the database, create a controller.js file.
Import MySchema from the model fileconst Task = require('./model');
Add a task to a task collection. This will define the POST route.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
exports.createTask = async (req, res) => {
try {
// get the task from the body
const taskData = await req.body;
//create a new task then save
await 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"
})
}
}
Add this code to the controller.js file. This will define the GET route.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
exports.createTask = async (req, res) => {
try {
// get the task from the body
const taskData = await req.body;
//create a new task then save
await 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 response
try {
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 to execute the above controllers. Create a new file and call it routes.js and add the following code:
1 2 3 4 5 6 7 8
const router = require("express") .Router() const controller = require('./controller') router .post('/', controller.createTask) .get('/', controller.getTasks) module.exports = router
Finally, execute these routes inside the server.js file.
1 2
const router = require('./routes') app.use('/tasks', router)
To add a new task, send a POST request using postman as follows:
To retrieve the added tasks, send a GET request using postman as follows:
You can also view the added tasks by accessing your MongoDB database:
I hope you found this helpful!