In this informative video tutorial, we’ll guide you through the process of connecting your Node.js and Express application to MongoDB, one of the most popular NoSQL databases. Whether you’re a beginner or an experienced developer, this tutorial will provide you with step-by-step instructions on how to set up your environment, install the necessary packages, and write the code required to seamlessly connect your Node.js and Express application to MongoDB. By the end of this video, you’ll have a clear understanding of how to leverage the power of MongoDB to efficiently manage and store your data in your Node.js and Express application. So, if you’re looking to enhance your web development skills, be sure to check out this tutorial!
You need to have npm and nodejs installed
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const PORT = 8000;
const uri =
"mongodb+srv://norbert:norbert@youtubetest.ogxp0ip.mongodb.net/?retryWrites=true&w=majority";
async function connect() {
try {
await mongoose.connect(uri);
console.log("Successful connection to MongoDB");
} catch (error) {
console.log(error);
}
}
connect();
app.listen(PORT, () => console.log(`Server started on ${PORT}`));
This is a simple Node.js and Express application that uses the Mongoose library to connect to a MongoDB database. The code initializes an Express app and sets the port to 8000. Then, it defines the URI for the MongoDB database and creates an async function called connect
that attempts to connect to the database using the await mongoose.connect(uri)
command. If the connection is successful, a message is logged to the console. If there is an error, it is caught and logged to the console. Finally, the app is set to listen on the specified port using the app.listen(PORT)
command. This code can be used as a starting point for building a Node.js and Express app that connects to a MongoDB database.
Want to become a web developer ?
Get complete web development courses on HTML, CSS , JavaScript, Bootstrap, Visual Studio Code, Responsive design and much more…